For a C++ std::string, call length() or size(); they return the same number. For a null-terminated C-style character string, use std::strlen() from <cstring>. Which function is right depends on the kind of string you have.
Length of a std::string
The usual C++ string type is std::string, an alias for std::basic_string<char>. Its member functions length() and size() both report how many character elements the string currently contains. They take no arguments and are interchangeable for this purpose:
#include <iostream>
#include <string>
int main() {
std::string word = "hello";
std::cout << word.length() << '\n'; // 5
std::cout << word.size() << '\n'; // 5
}
Use either spelling consistently in your code. size() is familiar from many standard-library containers, while length() can read especially clearly when the value represents text. There is no difference in the result, performance, or meaning for a std::string.
What the functions return
The result is the number of stored char elements, not the number of visible symbols on screen. A string can contain spaces, punctuation, or a null character, and those elements count too. An empty string has a length of zero. For example, after std::string name = "Ada Lovelace";, both name.length() and name.size() return 12, including the space.
The return type is the string type’s size_type, an unsigned size type used to represent container sizes. It is commonly compatible with std::size_t, but code that needs the exact declared type can use std::string::size_type. When comparing a length with an integer, be aware that mixing signed and unsigned values can produce compiler warnings or surprising comparisons if a negative signed value is involved.
How to use the result in code
Store the result with auto when you do not need to name its type, or use the string’s size_type for an explicit declaration. Here is a typical check:
std::string password = "example";
if (password.size() < 8) {
std::cout << "Too short\n";
}
The comparison above checks a basic minimum length; it does not establish that a password is secure. In loops, a length can also be used as a boundary. For example, if text is a string, valid character positions run from zero through text.size() - 1 when the string is nonempty. A loop using i < text.size() avoids trying to access the position immediately after its last character.
Keep the empty case in mind when calculating the last index. Subtracting one from an unsigned size of zero does not produce a useful negative index; it wraps to a large positive value. If you need to access the final character, first check that the string is not empty, or use a suitable operation such as back() only after that check.
When to use std::strlen
std::strlen() is for a null-terminated C-style string: a sequence of characters that ends at the first '\0' character. Include <cstring> and pass it a valid pointer to such a sequence:
#include <cstring>
#include <iostream>
int main() {
const char* message = "hello";
std::cout << std::strlen(message) << '\n'; // 5
}
Unlike std::string::length(), strlen does not know a separate stored length. It scans from the pointer until it encounters a null terminator. Therefore, its input must point to accessible memory containing a terminator; otherwise, reading onward has undefined behavior. It also cannot report characters after an embedded null because it treats that first null as the end.
Do not call strlen on a std::string object itself: the object is not a character pointer. If you specifically need to pass its character data to an older C API, use c_str() where a null-terminated view is required. For the string’s length, keep using size() or length().
Length, bytes, and Unicode text
A common point of confusion is whether string length means bytes, Unicode characters, or user-perceived symbols. For std::string, it means stored char elements. If the contents are UTF-8, those elements are bytes, and one visible character may occupy multiple bytes. For instance, a UTF-8 accented letter or emoji can contribute more than one to size(), depending on its encoding.
This is not a defect in std::string; the type stores a sequence of char values and does not automatically interpret that sequence as Unicode text. If an application needs a count of Unicode code points or user-perceived grapheme clusters, it needs Unicode-aware processing rather than simply calling length(). Grapheme clusters matter because a displayed symbol can be made from several code points, such as a base letter and a combining accent.
std::wstring also has size() and length(), but its elements are wchar_t values, not guaranteed to correspond one-for-one with user-visible characters. The width and use of wchar_t vary by platform. Choosing a wide string alone does not solve every Unicode counting or encoding problem.
Embedded null characters and array sizes
A std::string can store a null character within its contents. For example, a string constructed with an explicit length can contain '\0' before its end, and size() still counts that element and anything after it. This is one practical difference from a C-style string, whose conventional length ends at its first null terminator.
Character arrays can cause a related mistake. In const char text[] = "cat";, the array has four elements: the three letters plus the terminating null. sizeof(text) is therefore four in the scope where it is still an array. That is not generally a replacement for a string-length function: once an array is passed to a function as a pointer, its array size is no longer carried along, and an array may also contain data that is not a null-terminated text string.
For a literal known at compile time, subtracting one from its array size can exclude its terminating null, but that technique has narrow assumptions. For ordinary C++ text that may change at runtime, use std::string and ask the object for its size.
Choosing the right function
- You have a
std::string: usetext.size()ortext.length(). Prefer one style throughout a project. - You have a null-terminated
const char*: usestd::strlen(pointer)only when the pointer is valid and terminated. - You have a bounded character buffer: use the length information supplied by the API or buffer; do not assume it is safely null-terminated.
- You have a
std::string_view: use itssize()orlength(). A view stores a range length and does not require a terminator at the end. - You need visible Unicode character counts: use a Unicode-aware library or algorithm suited to the exact unit you need to count.
std::string_view is available from C++17 and is useful for read-only access to a character sequence without owning a copy. Its length is still a count of char elements, usually bytes for UTF-8. As with other non-owning views, the underlying data must remain valid for the view’s use; a view does not extend the lifetime of the characters.
Common mistakes to avoid
- Using
strlenas a string member: writetext.length(), nottext.strlen().strlenis a separate function in the C string library. - Assuming one byte equals one displayed character: this is not generally true for UTF-8 or other multibyte encodings.
- Passing an unterminated buffer to
strlen: the function has no buffer-bound argument and may read beyond the buffer. - Confusing length and capacity:
size()reports elements currently in the string.capacity()reports how many elements can be held before the string must allocate more storage; it is not the current length. - Using a signed index without checking conversions: string sizes are unsigned. Choose compatible types or validate values before comparing and indexing.
For performance, size() and length() on std::string provide the stored size directly; they do not need to scan for a terminator. By contrast, strlen must search through the characters up to the first null. Avoid repeatedly calling strlen on a long C string inside a loop when you can compute or retain its length once. For a standard string, querying its size is constant-time.
Frequently Asked Questions
Is length() or size() better in C++?
Neither is better for a std::string; they return the same value. size() matches the naming used by many containers, while length() can make text-oriented code read naturally. Pick the spelling that best fits the surrounding code.
What is the function for the length of a C++ string?
For std::string, call its length() or size() member. For a C-style null-terminated character sequence, call std::strlen() after including <cstring>.
Does std::string::length() count the null terminator?
It counts the characters stored as part of the string, not an extra terminator maintained for C-string access. If the string itself contains an embedded null character, that character is part of its stored content and is counted.
Does std::string::size() count Unicode characters?
Not necessarily. It counts char elements. With UTF-8 text, that means bytes, so a Unicode character may contribute several to the returned value. Use Unicode-aware logic when the requirement is to count code points or displayed grapheme clusters.
Can I use sizeof to find a string’s length?
Not for a general std::string or a character pointer: sizeof reports the size of the object or pointer, not the number of characters in the text. It can report the full size of a character array in the scope where the array type is known, including a literal’s terminating null, but it is not a general text-length function.
Related
- JavaScript String Split: Syntax, Examples, and Tips
- JavaScript split(): How to Use It and Avoid Pitfalls
- Python Logging F-Strings: When to Use Them and Why
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- XLOOKUP Case Sensitivity: How Excel Matches Text ValuesNo. In Excel for Microsoft 365, XLOOKUP is not case-sensitive: it treats text such as “Maple,” “MAPLE,” and…
- Excel Table Formulas: Do They Fill Down Automatically?Yes. In Microsoft Excel for Microsoft 365 on Windows, a formula entered in a table column normally fills…
- Monthly Loan Payment Formula in ExcelTo calculate a fixed monthly loan payment in Excel, use PMT. With the loan principal in B1, the…
- Copy Values Without Formulas in Excel: Step-by-StepTo copy formula results without copying the formulas in Excel for Microsoft 365 on Windows, select the cells,…
- Replace Multiple Words in Excel: Methods and FormulasTo replace several different words in Excel, use Ctrl+H and run Find and Replace once for each word,…
- Excel COUNTIF and SUMIF With Dates: Practical ExamplesTo count or sum rows by date in Excel, use COUNTIF or SUMIF with a date criterion; for…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.