C/C++ Arena

Step 3 of 6

Write your own strlen

Library functions aren't magic. strlen is a short loop, and writing it yourself is the best way to really understand how C strings work.

The idea: start at index 0 and move forward one character at a time until you find '\0'. The index where you stop is the length, because indexes start at 0. Here's the same kind of loop counting something else, the number of spaces:

#include <stdio.h>

int count_spaces(const char s[]) {
    int count = 0;
    for (int i = 0; s[i] != '\0'; i++) {
        if (s[i] == ' ') {
            count++;
        }
    }
    return count;
}

int main(void) {
    printf("%d\n", count_spaces("to be or not to be"));
    printf("%d\n", count_spaces(""));
    return 0;
}
5
0

The loop condition is the key

s[i] != '\0' is the standard way to walk a string: the loop body runs for every real character and stops at the terminator. You don't need the length in advance, which is the whole point of the terminator. (Since '\0' is 0 and 0 is false, you'll often see the shorter for (int i = 0; s[i]; i++).)

Empty strings

"" is a string whose very first character is '\0'. A correct loop handles it naturally: the condition is false immediately, the body never runs, and the result is 0. Always check your string functions against the empty string.

const

const char s[] promises that the function only reads the string. If the body tried s[0] = 'x', the compiler would refuse. It also tells callers it's safe to pass string literals like "hello", which must never be modified.

Your turn: write int my_strlen(const char s[]) without using <string.h>.

Previous: strlen and friends Next: Compare strings correctly