basics · beginner · ~15 min

Implement my_strlen

Walk a C string to its NUL terminator.

Challenge

Measure the length of a C string yourself, the way strlen does.

Task

Implement size_t my_strlen(const char *s) that returns the number of characters in s before the terminating NUL byte. Do not call strlen.

Input

A NUL-terminated string s.

Output

Returns the character count (excluding the NUL) as a size_t.

Example

my_strlen("hello")   ->   5
my_strlen("")        ->   0
my_strlen("a")       ->   1

Edge cases

  • The empty string has length 0.

Rules

  • Do not call strlen — walk the string yourself.

Input format

A NUL-terminated string s.

Output format

The number of characters before the NUL, as a size_t.

Constraints

Do not call strlen.

Starter code

#include <stddef.h>

size_t my_strlen(const char *s) {
    /* TODO */
    return 0;
}

Common mistakes

Forgetting NUL terminator '\0'; off-by-one with string indexing; reading out of bounds; modifying read-only string literal.

Edge cases to handle

Empty string ""; single-character string; string with spaces or special characters; string without match.

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.