In C++, get the length of a std::string with its size() or length() member function; they return the same value. For example, if text is a string, text.size() reports how many characters it contains, not counting any terminating null character used internally.
The basic string length functions
The standard C++ string type, std::string, is an alias for std::basic_string<char>. Its size() member returns the number of char elements currently stored in the string. The synonymous length() member returns exactly the same count. Both are commonly used, and choosing between them is mostly a matter of style.
#include <iostream>
#include <string>
int main() {
std::string text = "Hello, C++!";
std::cout << text.size() << '\n'; // 11
std::cout << text.length() << '\n'; // 11
}
The result is 11 because the text has eleven stored characters, including the comma, spaces, and exclamation mark. The quotes in the source code are not part of the string. Include <string> to use std::string; include <iostream> here only because the example prints the values.
You can call either member on a string variable or on a temporary string expression. In ordinary code, a named variable is easier to read and reuse. The important point is that these are member functions, so the call uses a dot: text.size(), not size(text).
What the returned number means
For std::string, the count is the number of stored char elements. In typical implementations, each char holds one byte, so the result is often described as a byte count. That description is especially useful when dealing with UTF-8 text, but it is not the same thing as counting human-perceived characters. A displayed symbol may be represented by multiple bytes.
For example, the letter A in ordinary ASCII-compatible text takes one byte in a std::string. A UTF-8 character such as many accented letters or emoji can take several bytes. Therefore, a string containing one visible emoji may have a size() greater than one. The function is reporting the string’s stored elements; it is not decoding Unicode or counting grapheme clusters, which are the units people generally perceive as individual characters.
This distinction also applies to other string specializations. A std::wstring has a size() that counts its wchar_t elements, not necessarily Unicode characters. The width and encoding associated with wide strings depend on the platform and implementation. If an application needs user-visible character counts, it needs Unicode-aware processing appropriate to its encoding rather than assuming that size() provides that count.
size() versus length()
There is no difference in the value returned by std::string::size() and std::string::length(). Both are standard member functions, both are constant-time operations, and either is valid for checking a string’s current length. The two names exist as convenient ways to express the same property.
size()is a familiar name across many standard containers, includingstd::vectorandstd::array. It can make code that works with different container types feel consistent.length()can read naturally when the code is specifically discussing text, such as “the length of the username.”- In a codebase, consistency with its existing style is usually more valuable than switching between the two names.
Do not confuse size() with capacity(). The size is the number of characters currently in the string. Capacity is how many characters the string can hold in its currently allocated storage before it needs to obtain more space. For instance, a string may have a size of 5 and a capacity of 15. Only the first five characters belong to its current value.
Checking whether a string is empty
If the question is whether a string contains any characters, use empty(). It returns true when the size is zero and false otherwise. This communicates the intent more directly than comparing the length with zero.
if (text.empty()) {
std::cout << "No text was provided.\n";
}
text.empty() is equivalent in result to text.size() == 0. It does not treat spaces as empty: a string containing three spaces has a size of three. If an application considers whitespace-only input to be blank, it must separately examine or trim the characters. Likewise, a string containing an embedded null character is not empty if that character is part of its stored contents.
Length of a C-style string
A null-terminated C-style string is different from a std::string. For a valid C string, the C library function std::strlen counts characters up to, but not including, the first null character ('\0'). Declare it by including <cstring>.
#include <cstring>
#include <iostream>
int main() {
const char* text = "Hello";
std::cout << std::strlen(text) << '\n'; // 5
}
strlen requires its argument to point to a null-terminated character sequence. If there is no null terminator in the accessible memory, calling it can read beyond the intended array, causing undefined behavior. It also has to scan the characters to find the terminator, so its running time grows with the string length. By contrast, a std::string keeps track of its size, and its size() operation is constant time.
There is an important embedded-null difference. A std::string can store '\0' as an ordinary element and can also store characters after it. Its size() counts all stored elements. If you pass its data to a C function that expects a null-terminated string, that function may stop at the first embedded null. Do not use strlen(text.c_str()) as a general substitute for text.size(); it may return a smaller count, and size() is the direct operation for a C++ string.
String literals, arrays, and sizeof
A common source of confusion is the difference between a string’s length and the size of the array holding a string literal. The literal "cat" has three visible characters followed by a terminating null character when represented as a character array. Consequently, sizeof("cat") is 4: it measures the whole array in bytes, including the terminator. A std::string initialized from that literal has a size of 3 because the terminator is not part of its value.
For a fixed character array, sizeof(array) measures the whole array’s storage, not necessarily the number of characters before its null terminator. For a pointer such as const char* p, sizeof(p) measures the pointer itself, not the text it points to. Use std::strlen for a valid null-terminated C string, or use std::string::size() for a C++ string.
There is a related constructor pitfall: initializing a std::string from a plain C string uses its terminating null to determine where the text ends. If the source data can contain embedded nulls or is not null-terminated, provide an explicit length when constructing or assigning the string. For example, the pointer-and-count constructor can preserve embedded nulls:
const char raw[] = {'A', '\0', 'B'};
std::string text(raw, sizeof raw);
// text.size() is 3
Using the length safely in code
The return type of std::string::size() is the string’s unsigned size_type, rather than necessarily being an int. This matters in comparisons and loops. Comparing a signed integer with an unsigned size can produce compiler warnings or surprising behavior, particularly if the signed value is negative. Prefer the string’s own size type when storing a size, or use a loop form that does not introduce a mismatched signed counter.
for (std::string::size_type i = 0; i < text.size(); ++i) {
std::cout << text[i] << '\n';
}
Modern C++ also supports range-based loops when an index is not needed: for (char ch : text) visits each stored character. If you do need an index, remember that valid character positions run from zero through text.size() - 1 when the string is nonempty. The position equal to text.size() is the end position, not an index for a character. Accessing an out-of-range position with operator[] is unsafe; use at() if you want bounds checking that throws an exception for an invalid position.
Lengths are useful for validation, but define the rule carefully. A requirement such as “at most 20 characters” could mean at most 20 bytes, code units, Unicode code points, or visible grapheme clusters. Checking text.size() <= 20 enforces a limit of 20 stored char elements. That may be appropriate for ASCII identifiers or a byte-oriented protocol, but it may reject or miscount multilingual text if the requirement is about what a person sees.
Alternatives for non-owning text
If a function only needs to inspect text and should not own a copy, std::string_view can be useful in C++17 and later. It represents a view of a character sequence and offers size(), length(), and empty() with the same basic meanings. A view does not own or extend the lifetime of the characters it refers to, so it must not outlive the underlying data. Its length is still a count of stored character elements, not a Unicode character count.
For example, a function can accept std::string_view to read either a std::string or a compatible character sequence without requiring a new string allocation. Include <string_view> and use the feature with a C++17-or-newer compiler mode. For long-term storage or modification, an owning std::string is generally the more appropriate type.
Frequently Asked Questions
Is string.length() the same as string.size() in C++?
Yes. For std::string, both member functions return the number of stored char elements. Use whichever name fits the surrounding code style.
How do I get the length of a string array?
If it is a std::string, call size() or length(). For a valid null-terminated C string, call std::strlen after including <cstring>. Do not use sizeof on a pointer to try to measure the text.
Does size() count the null terminator?
No. A std::string‘s size counts the elements in its value and excludes the terminator maintained for C-string interoperability. An embedded '\0' that was explicitly stored in the value does count as an element.
Does std::string::size() count Unicode characters?
Not in general. It counts stored char elements. With UTF-8, one visible character may occupy multiple elements, so counting code points or user-perceived characters requires Unicode-aware processing.
Should I use size() or strlen()?
Use size() for std::string. Use std::strlen only for a valid null-terminated C string. They have different requirements, and strlen stops at the first null byte.
What function checks whether a string has length zero?
Use empty(), as in text.empty(). It clearly expresses an emptiness check and returns the same condition as text.size() == 0.
Related
- Split by Position in Power Query: A Practical Guide
- TinyTask for Sol’s RNG: What It Can and Can’t Do Safely
- Java split() Method: Split Strings with Regex and Limits
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Heat Map Conditional Formatting: Setup and TipsIn Excel for Microsoft 365 on Windows, select the numeric cells, then choose Home > Conditional Formatting >…
- How to Open an Excel File That Is Too LargeIf an Excel file is too large to open, first save a copy to your computer, then try…
- Excel Remove Duplicates: Keep the Last Matching RecordExcel’s Remove Duplicates command keeps the first matching row it encounters; it has no built-in option to keep…
- Excel Cell Service in Jurong East: What to CheckIf you mean a business called “Excel Cell Service” in Jurong East, I can’t reliably confirm that such…
- Create a Table in Excel With a Title: Step-by-StepTo create a table in Excel with a title, type the title in a row above your data,…
- How to Merge Cells in Jupyter Notebook: A Practical GuideTo merge cells in Jupyter Notebook, select the adjacent cells you want to combine, then choose the merge…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.