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.cint 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:
- Initialize a counter
ito 0. - Loop while
str[i]is not'\0', incrementingieach iteration. - When the loop ends,
iholds 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.