How to find the length of a string in C
By Flavio Copes
Learn how to find the length of a string in C using the strlen() function from the string.h standard library, which returns the length as an integer.
Use the strlen() function provided by the C standard library string.h header file.
char name[7] = "Flavio";
strlen(name);
This function will return the length of a string as an integer value.
Working example:
#include <string.h>
#include <stdio.h>
int main(void) {
char name[7] = "Flavio";
size_t length = strlen(name);
printf("Name length: %zu", length);
}
This prints Name length: 6.
Notice the return type. strlen() returns a size_t, an unsigned integer type, and the matching printf format specifier is %zu.
How does strlen() work?
Strings in C are arrays of characters ending with a special character: the null terminator, written as \0.
strlen() walks the array from the start and counts characters until it finds that terminator. The terminator itself is not counted.
That’s why "Flavio" has a length of 6, even though we declared the array with size 7. The seventh slot holds the \0 that marks the end.
strlen() vs sizeof
These two are easy to confuse, and they answer different questions:
char name[7] = "Flavio";
strlen(name); //6
sizeof(name); //7
sizeof gives you the size of the array in bytes, terminator included. strlen() gives you the length of the string stored in it.
The difference matters more when the array is bigger than the string:
char city[20] = "Rome";
strlen(city); //4
sizeof(city); //20
Use strlen() when you care about the text, sizeof when you care about the memory.
Be careful with the null terminator
strlen() trusts that the terminator is there. If it’s not, the function keeps reading past the end of your array, through whatever memory comes next. That’s undefined behavior, and the result is garbage at best, a crash at worst.
C lets you create this situation without any warning:
char name[6] = "Flavio";
This is legal C. The array holds exactly the 6 letters, and there’s no room left for the \0. Calling strlen(name) on it is a bug.
The fix is to size the array with one extra slot, or better, let the compiler count for you:
char name[] = "Flavio";
With no explicit size, the compiler allocates 7 bytes, terminator included. That’s the form I use whenever the string is known upfront.