In C++, std::string::size() returns how many characters are stored in the string. Counting starts at 0 for an empty string.
For std::string, size() and length() return the same value. Prefer either name consistently. 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 size with empty brackets.
C++
std::size_t n = s.size();
std::cout << n;
Call
What it does
s.size()
Returns the current character count as std::size_t.
size() does not count a C-string terminator inside the std::string object. c_str() adds a '\\0' for C APIs, but that extra byte is not part of size().
Library declarations
C++
size_type size() const noexcept;
Parameters
Parameter
Description
None
size() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
size_type
Usually std::size_t. The number of characters currently stored.