In C++, std::string::length() returns the character count of the string. For std::string it is the same as size().
Beginners often prefer length() because it sounds like text. Library code often uses size() to match other containers. Include <string>.
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax
Call length with empty brackets.
C++
std::size_t n = s.length();
Call
What it does
s.length()
Returns the current character count. Same as s.size().
Do not mix this up with strlen from <cstring>. strlen walks a C-string until '\\0'. length() reads the stored size of a std::string.
Library declarations
C++
size_type length() const noexcept;
Parameters
Parameter
Description
None
length() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
size_type
Number of characters in the string.
C++ Examples
Example 1 — Basic length()
Measure a short word.
C++
#include <iostream>
#include <string>
int main() {
std::string word = "fun";
std::cout << word.length() << '\n';
return 0;
}