Skip to main content

ft_strlen — String Length

Allowed functions: none

Write a function that returns the length of a string.

int	ft_strlen(char *str);

Solution

Download ft_strlen.c
int ft_strlen(char *str) {
int i = 0;
while (str[i]) {
i++;
}
return i;
}

How It Works

Goal: Return the number of characters in a string, not counting the null terminator.

Approach: Increment a counter while iterating through the string until the null terminator is found.

Step by step:

  1. Initialize a counter i to 0.
  2. Loop while str[i] is not '\0', incrementing i each iteration.
  3. When the loop ends, i holds the string length — return it.

Key concept: Null-terminated strings — in C, strings have no built-in length; the only way to know where they end is to find the '\0' character.