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;
}

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