Getting length with strlen
What you'll learn: How to use the strlen function to count the number of visible characters in a string without including the null terminator.
The character counter
In C, a string is just an array of characters ending with a hidden "stop sign" called the null terminator (\0). When you want to know how long a string is, you don’t want to count every single slot in the array, nor do you want to count that hidden stop sign. You only care about the readable text.
The strlen function (short for "string length") does the manual labor for you. It starts at the beginning of your string and counts every character one by one until it hits the \0.
How to use it
To use strlen, you must include the <string.h> header at the top of your code. The function takes the string as an input and returns a number (specifically of type size_t, which is a positive integer).
Think of it like a tape measure for text. If you have a box (an array) that can hold 50 items, but you only put 5 items inside, strlen tells you there are 5 items, not that the box is size 50.
#include <stdio.h>
#include <string.h>
int main() {
// An array that can hold 20 characters
char username[20] = "Coder123";
// strlen counts 'C', 'o', 'd', 'e', 'r', '1', '2', '3'
int length = strlen(username);
printf("The username is %d characters long.\n", length);
return 0;
}
Length vs. Size
It is vital to distinguish between length and size:
- Size (
sizeof): This tells you how much memory the array occupies. In the example above,sizeof(username)would be 20 because the array was declared with 20 slots. - Length (
strlen): This tells you how much data is actually in the array. In the example,strlen(username)is 8.
If you tried to measure an empty string "", strlen would return 0, because the very first character it sees is the null terminator stop sign.
Key takeaway
Use strlen() from <string.h> to find the number of visible characters in a string, excluding the null terminator.