Finding string length with strlen
What you'll learn: How to use the strlen function to calculate the number of visible characters in a string.
The character counter
In C, strings are not a special data type that "knows" how long they are. Instead, they are just arrays of characters ending with a hidden marker called the null terminator (\0). If you want to know how many letters are in a word, you need a way to count them until you hit that marker.
Rather than writing a manual loop every time, the C Standard Library provides a handy tool called strlen (short for string length).
Think of strlen like a tape measure. When you hand it a string, it starts at the first letter and counts forward one by one. The moment it sees the "null terminator" at the end, it stops counting and gives you the total.
Using strlen in code
To use strlen, you must include the header file <string.h> at the top of your program. This file acts as the toolbox containing all string-related functions.
It is important to remember one crucial rule: strlen does not count the null terminator. If your string is "Cat", strlen returns 3, even though the computer is technically using 4 bytes of memory to store it (C, a, t, and \0).
#include <stdio.h>
#include <string.h>
int main() {
char greeting[] = "Hello!";
// We use %zu because strlen returns a type called size_t
printf("The word is: %s\n", greeting);
printf("Length: %zu\n", strlen(greeting));
return 0;
}
Why size_t?
You might notice the %zu formatter in the code above. strlen doesn't return a standard int; it returns a size_t. This is just a special type of unsigned integer used specifically for sizes and lengths. Because a string cannot have a "negative" length, size_t ensures the number is always zero or greater.
The common pitfall
New programmers often confuse strlen with sizeof.
sizeoftells you how much physical space the array occupies in memory.strlentells you how many characters are currently inside that space.
If you have a large suitcase (an array of 100) but only packed two shirts (a string of 2), strlen will correctly tell you 2, while sizeof would tell you 100.
Key takeaway
Use strlen from <string.h> to count the visible characters in a string, excluding the null terminator.