Skip to content
Devtoolry

Strings · beginner

C Program to Find the Length of a String Without strlen()

Find the length of a string in C without strlen() by counting characters up to the null terminator, with an index loop and with pointer subtraction.

A C string is a sequence of chars ending with '\0'. Its length is the number of characters before that terminator, which is exactly what strlen() counts. Writing it yourself shows how C strings work, and why sizeof gives a different answer.

The program

C
#include <stdio.h>
#include <string.h>

size_t my_strlen(const char *s) {
    size_t length = 0;
    while (s[length] != '\0')
        length++;
    return length;
}

int main(void) {
    char text[20] = "Hello, C";
    printf("my_strlen: %zu\n", my_strlen(text));
    printf("strlen:    %zu\n", strlen(text));
    printf("sizeof:    %zu\n", sizeof text);
    printf("empty:     %zu\n", my_strlen(""));
    return 0;
}
Output
my_strlen: 8
strlen:    8
sizeof:    20
empty:     0

How it works

  1. length starts at 0 and counts up while s[length] is not the terminator.
  2. For "Hello, C" the loop stops at index 8, where the '\0' is.
  3. size_t is the type for sizes and lengths; %zu prints it.
  4. sizeof text is 20, the size of the whole array, no matter how much of it the string uses.

Another way: With pointer subtraction

Move a pointer to the terminator and subtract the start address. The difference of two pointers into the same array is the number of elements between them.

C
#include <stdio.h>

size_t length(const char *s) {
    const char *p = s;
    while (*p)
        p++;
    return (size_t)(p - s);
}

int main(void) {
    printf("%zu %zu\n", length("pointer"), length(""));
    return 0;
}
Output
7 0

Common mistakes

  • Using sizeof to get the length of a string: it gives the array size (or the pointer size for a char *).
  • Forgetting room for '\0': "Hello" needs an array of at least 6 chars.
  • Calling strlen() on a char array that was filled without a terminator, which reads past the end of the array.

Try it yourself

  • Write my_strcpy() and my_strcat() the same way.
  • Count only the letters in a string, ignoring spaces and punctuation.

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.