String Length
Lesson outline
Getting String Length
You can determine the number of characters in a string using the length() or size() methods (they are equivalent in C++). Both run in O(1) time and return std::string::size_type (an unsigned type).
Empty Strings
You can check if a string has no characters using the empty() method, which returns true (1) if the string is empty.
Length vs Capacity
A string stores both its length (the number of code units it currently holds) and its capacity (the amount of memory allocated). Capacity may be larger than length to reduce reallocations when the string grows.
Unicode Caveat (UTF-8)
In a narrow std::string, size()/length() count bytes, not human-visible characters. With UTF-8 text, multi-byte code points (e.g., emoji) make size larger than the perceived character count.
If you need code-point counts in UTF-8, you can approximate by counting non-continuation bytes; for true user-perceived characters (grapheme clusters), a text library is required.
Best Practices
- Prefer
'\n'overstd::endlto avoid needless flushing. - Remember
size()is unsigned; take care when subtracting or comparing with signed values. - Use
reserve()to pre-allocate when you know growth ahead of time;shrink_to_fit()is non-binding. - For international text, be explicit about encodings; consider
std::u8string/std::u32stringor a Unicode library for advanced needs.