Home C++ Strings Functions strlen() C++ strlen() Function Definition In C++, strlen() counts the characters in a C-string. It starts at the first character and stops when it reaches the ending '\0'. That ending mark is not included in the count.
You pass one string. "Hello" returns 5, and an empty string "" returns 0. The string must already end with '\0', or the count can run past the array. Include <cstring>.
Syntax Pass the C-string you want to measure.
Call What it does strlen("Hello")Counts the letters in Hello. The result is 5.
Library declarations size_t strlen(const char* str); Parameters Parameter Description str Required. The C-string to measure. It must end with '\0'.
Return Value Return Value Description Length How many characters come before '\0'. 0 The string is empty, like "".
C++ Examples 1. Basic length 2. vs sizeof 3. vs std::string Example 1 — Basic strlen() Count the characters in a greeting.
#include <iostream>
#include <cstring>
int main() {
const char* text = "Hello";
std::cout << "Length: " << std::strlen(text) << '\n';
return 0;
} How It Works "Hello" has five letters.The hidden '\0' ends the string but is not counted. Result type is size_t. Example 2 — strlen vs sizeof Array storage includes the null terminator; strlen does not.
#include <iostream>
#include <cstring>
int main() {
char text[] = "Hello";
std::cout << "strlen: " << std::strlen(text) << '\n';
std::cout << "sizeof: " << sizeof text << '\n';
return 0;
} How It Works strlen counts visible characters: 5.sizeof text is the array size: 5 letters + '\0' = 6.Do not confuse array bytes with string length. Example 3 — Prefer std::string::size() Same idea with modern C++ strings.
#include <iostream>
#include <string>
int main() {
std::string text = "Hello";
std::cout << "size: " << text.size() << '\n';
return 0;
} How It Works size() returns the stored length.No need to scan for '\0' yourself. Learn strlen for C-strings; prefer size() for std::string. Frequently Asked Questions What does strlen() do in C++? strlen() counts the characters in a C-string and stops before the ending null character. That null is not included in the count.
What is the parameter of strlen()? str is the C-string to measure. It must end with a null character.
What does strlen() return? The number of characters before the null. An empty string returns 0.
Does strlen() count the null character? No. The ending null marks where the count stops, and it is not included.
When should I use strlen() instead of std::string::size()? Use strlen() for a char* C-string. For a std::string, use size() or length().
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful
Helpful Share Copy link Suggestion