The strlen() function answers a basic question: how long is this C-string? It counts characters from the start until (but not including) the null terminator '\0'. Knowing length helps you loop over text, validate input, and size buffers before calling functions like strcpy().
01
Count Chars
Before \0.
02
size_t Return
Unsigned count.
03
Not STL
<cstring> API.
04
+1 Rule
Room for \0.
05
vs size()
std::string length.
06
O(n) Scan
Walk every char.
Fundamentals
Definition and Usage
In C++, strlen() is declared in <cstring>. It accepts a pointer to a null-terminated C-string and returns the number of bytes (for plain char text, the number of characters) before the terminating '\0'.
String literals like "Hello, C++!" automatically include a hidden null terminator at the end. strlen sees 11 visible characters and stops—it never counts the twelfth byte that holds '\0'.
💡
Beginner Tip
When allocating memory for a copy with strcpy, allocate strlen(source) + 1 bytes. The extra byte holds the null terminator that strlen does not count.
Foundation
📝 Syntax
Function signature and a typical call:
C++
#include <cstring>
size_t strlen(const char* str);
// Example:
std::size_t len = strlen("Hello, C++!");
// len == 11
Parameters
str — pointer to a null-terminated C-string (literal, char array, or const char*).
Return Value
Returns a size_t equal to the number of characters before the first '\0'. An empty string "" has length 0.
Cheat Sheet
⚡ Quick Reference
String
strlen result
Notes
"hi"
2
Does not count \0
""
0
Empty string
"Hello, C++!"
11
Spaces and symbols count
std::string s
Use s.size()
Not strlen
Length
strlen(str)
Character count
Buffer
strlen(s) + 1
For strcpy
Empty?
strlen(s) == 0
No characters
Include
#include <cstring>
Header file
Hands-On
Examples Gallery
Compile with g++ strlen.cpp -std=c++17 -o strlen. Each example shows a practical way to use or relate to strlen().
Both report 8 characters for "Tutorial". Use strlen only on null-terminated C-strings; use .size() or .length() on std::string objects.
Example 5 — Loop Using Cached Length
Call strlen once, then iterate—avoid repeated scans in the loop condition.
C++
#include <iostream>
#include <cstring>
int main() {
const char* word = "strlen";
std::size_t len = std::strlen(word);
std::cout << "Characters: ";
for (std::size_t i = 0; i < len; ++i) {
std::cout << word[i];
if (i + 1 < len) {
std::cout << '.';
}
}
std::cout << "\nTotal: " << len << "\n";
return 0;
}
📤 Output:
Characters: s.t.r.l.e.n
Total: 6
How It Works
Storing len once turns an O(n²) pattern (calling strlen every loop test) into O(n). You can also iterate until str[i] != '\0' without calling strlen at all.
Applications
🚀 Common Use Cases
Buffer allocation — compute strlen + 1 before strcpy or malloc.
Input validation — enforce minimum or maximum name lengths.
Loop bounds — iterate over each character in a C-string.
Formatting output — pad or align text based on length.
Interfacing with C APIs — many functions expect you to know string sizes.
🧠 How strlen() Works
1
Start at str[0]
Initialize counter to zero and read the first byte.
Start
2
Check for \0
If current byte is null terminator, stop scanning.
Test
3
Increment and advance
Otherwise add one to counter and move to the next character.
Loop
#
📏
Return count
The counter equals the string length excluding the null byte.
Important
📝 Notes
The argument must be a null-terminated C-string—otherwise behavior is undefined.
strlen is from the C library (<cstring>), not the C++ STL containers.
Do not pass a std::string object directly; use s.c_str() if you must call strlen on its content.
Time complexity is O(n) where n is the string length.
For binary data that may contain zero bytes, use a length-aware type instead of C-strings.
Performance
⚡ Optimization
Cache the result when you need the length more than once. Avoid writing for (i = 0; i < strlen(s); ++i) because strlen rescans from the start on every comparison. Prefer range-for over std::string, or loop until '\0' when working with C-strings in hand-written parsers.
Wrap Up
Conclusion
strlen() is the standard way to measure a C-string’s character count. Remember: it excludes '\0', requires a terminated string, and scans linearly. Pair it with the +1 rule whenever you allocate buffers.
Next, learn strncat() to append a bounded number of characters from one C-string to another—a slightly safer cousin of strcat().
Ensure strings are null-terminated before calling strlen
Use strlen(s) + 1 when sizing copy buffers
Cache length in a variable for loops and repeated use
Prefer std::string::size() in modern C++ code
Include <cstring> and use std::strlen
❌ Don’t
Call strlen in a loop condition each iteration
Pass char arrays missing a '\0' terminator
Assume strlen counts the null byte
Use strlen on binary data with embedded zeros
Confuse it with sizeof (array size vs text length)
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about strlen()
Use these points whenever you measure C-strings.
5
Core concepts
📏01
Char Count
Before \0.
Basics
🔢02
size_t
Unsigned return.
Return
➕03
+1 Byte
For terminator.
Buffers
🔄04
O(n) Scan
Cache result.
Perf
💬05
std::string
Use .size().
Modern
❓ Frequently Asked Questions
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. For example, strlen("hi") returns 2.
size_t strlen(const char* str); Include <cstring>. Pass a pointer to a null-terminated char array or string literal. The return type size_t is an unsigned integer type suitable for sizes and counts.
No. It stops when it reaches '\0' and returns the number of characters before it. To allocate a buffer for strcpy, you need strlen(src) + 1 bytes to hold both the text and the terminator.
strlen() works on C-strings (char arrays ending with '\0') and scans until the terminator. std::string::size() (or length()) returns the character count stored in a string object instantly without scanning. Prefer std::string in modern C++ when possible.
Undefined behavior. strlen() keeps reading memory until it finds a zero byte, which may crash the program or return a nonsense length. Always ensure C-strings are properly terminated.
O(n) in the length of the string because it must walk every character until '\0'. If you need the length repeatedly in a loop, store the result in a variable instead of calling strlen() on every iteration.
Did you know?
sizeof(arr) on a char array gives the total array size in bytes, while strlen(arr) gives the current text length. For char buf[100] = "hi";, sizeof buf is 100 but strlen(buf) is only 2.