basics · intermediate · ~15 min

Implement strlen

Walk a pointer through a NUL-terminated string and count the steps.

Challenge

Write your own strlen: count the bytes in a C string up to (not including) the NUL terminator.

Task

Implement size_t my_strlen(const char *s) returning the length of the NUL-terminated string s, excluding the terminator. No main — the grader calls it.

Input

A NUL-terminated string s (may be empty).

Output

The number of bytes before the terminating \0, as a size_t.

Example

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

Edge cases

  • Empty string returns 0.

Rules

  • Do not call the standard strlen (or any <string.h> length helper).

Why this matters

The smallest possible exercise that uses pointers, the string convention, AND pointer arithmetic. Get all three at once.

Input format

A NUL-terminated string s.

Output format

The byte count before the NUL, as a size_t.

Constraints

Do not call the standard strlen.

Starter code

#include <stddef.h>

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

Common mistakes

Returning int instead of size_t. Using s[i] index notation when pointer arithmetic is the idiom. Reading past the NUL.

Edge cases to handle

Empty string → 0. Embedded NUL → terminates at the first one. Very long strings → linear scan, fine.

Complexity

O(n) where n is the string length. Cannot be faster in the general case — you must touch each byte.

Background lessons

Up next

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