The strlen() function counts how many characters appear in a C-string before the terminating '\0'. It is one of the most frequently used functions in C—essential for allocating buffers, copying strings, and validating input.
01
Count Chars
Not \0.
02
size_t
Return type.
03
Empty = 0
"" length.
04
len + 1
Buffer size.
05
string.h
Standard C.
06
vs sizeof
Array bytes.
Fundamentals
Definition and Usage
A C-string is a sequence of bytes ending with a null character. strlen walks from the start until it finds that null byte and returns how many non-null characters it passed.
The count does not include '\0'. When allocating memory for a copy, use strlen(s) + 1 to leave room for the terminator. When checking whether a fixed buffer can hold a string, compare length to available space carefully.
💡
Beginner Tip
Print the result with printf("%zu\n", strlen(s));. The z length modifier matches size_t. Using %d can warn or misprint on some platforms.
Foundation
📝 Syntax
Standard C declaration:
C
size_t strlen(const char *s);
Parameter
s — pointer to a null-terminated C-string.
Return Value
Number of characters before '\0', as size_t.
0 for an empty string "".
Header
#include <string.h>
Cheat Sheet
⚡ Quick Reference
String s
strlen(s)
Bytes needed (with \0)
"Hello, C!"
9
10
""
0
1
"A"
1
2
char buf[32] = "Hi";
2
sizeof buf is 32
print
printf("%zu", strlen(s));
Length
len = strlen(s);
Char count
Alloc size
strlen(s) + 1
Include \0
Print
printf("%zu", len);
size_t
Array size
sizeof(buf)
Not length
Hands-On
Examples Gallery
Compile with gcc strlen.c -std=c11 -o strlen. Every example includes <string.h>.
📚 Getting Started
Measure the length of a simple string literal.
Example 1 — Basic String Length
Count characters in "Hello, C!".
C
#include <stdio.h>
#include <string.h>
int main(void) {
const char *message = "Hello, C!";
size_t length = strlen(message);
printf("The length of the string is: %zu\n", length);
return 0;
}
📤 Output:
The length of the string is: 9
How It Works
The nine visible characters are counted; the hidden '\0' at the end stops the scan but is not included in the result.
Example 2 — Empty String
An empty C-string still has a null terminator, but length zero.
strlen counts five letters before '\0'. sizeof buf is the whole array (20 bytes) fixed at compile time. Never use sizeof on a pointer expecting string length.
Example 5 — Loop Using Length
Print each character using an index from 0 to strlen - 1.
C
#include <stdio.h>
#include <string.h>
int main(void) {
const char *word = "C-string";
size_t i, n = strlen(word);
printf("Characters: ");
for (i = 0; i < n; i++) {
printf("%c ", word[i]);
}
printf("\nTotal: %zu\n", n);
return 0;
}
📤 Output:
Characters: C - s t r i n g
Total: 8
How It Works
Calling strlen once before the loop avoids recomputing length every iteration. For very hot loops on huge strings, pointer walking can be faster, but strlen once is clear and fine for beginners.
Applications
🚀 Common Use Cases
Buffer allocation — malloc(strlen(s) + 1) before copy.
Bounds checks — verify text fits before strcat or strcpy.
Input validation — enforce maximum name or password lengths.
Formatting — pad or align output based on text width.
Teaching C-strings — connect length to null termination.
🧠 How strlen() Works
1
Start at s[0]
Initialize counter to 0.
Scan
2
Check each byte
If not '\0', increment counter and advance.
Count
3
Stop at \0
Return counter without counting the terminator.
Stop
=
📏
size_t len
Character count excluding null byte.
Important
📝 Notes
Requires a null-terminated string—binary blobs need explicit lengths.
Time complexity is O(n)—scans the whole string each call.
Do not call strlen twice in a row on the same unchanged string in tight loops—cache the result.
sizeof(pointer) is pointer size, not string length.
Unicode code points are not counted—UTF-8 multibyte sequences count bytes.
Performance
⚡ Optimization
Library strlen is highly optimized. If you already know the length (for example from a length-prefixed protocol), store it instead of rescanning. Avoid strlen in inner loops when the string has not changed.
Wrap Up
Conclusion
strlen() returns how many characters precede the null terminator. Use %zu to print it, add one for buffer sizing, and never confuse it with sizeof on arrays.
Next, learn strcmp() to compare two strings lexicographically.
strlen() counts how many characters appear in a null-terminated C-string before the terminating '\0'. It does not include the null character in the count.
size_t strlen(const char* s); Include <string.h>. The argument must point to a valid null-terminated string.
No. If s is "Hello", strlen returns 5. The null byte marks the end but is not counted.
size_t—an unsigned integer type used for sizes and counts. Print it portably with printf("%zu", len).
strlen() counts characters until '\0' at runtime. sizeof on a char array returns the array size in bytes at compile time, which may be larger than the string length if the array is only partly filled.
Behavior is undefined. strlen keeps reading memory until it finds a zero byte. Always ensure C-strings are properly terminated.
Did you know?
The name strlen stands for string length. It has been part of C since the earliest standard library—every string function you learn (strcpy, strcat, strcmp) assumes you understand that C-strings end with '\0', which is exactly what strlen locates.