String Types
Lesson outline
Introduction to Strings
Strings in C++ are objects that represent sequences of characters.
They are provided by the Standard Library (std::string) and support convenient operations for text handling, unlike primitive C-style character arrays.
String Families (What "string" can mean in C++)
C++ provides several string-like types. Choose based on ownership, encoding, and performance needs:
| Type | Owns Storage? | Typical Use | Notes |
|---|---|---|---|
| std::string | Yes | General UTF-8/text bytes | Counts bytes; encoding is by convention (often UTF-8). |
| std::string_view (C++17) | No | Non-owning view into string data | Cheap slicing/parameters; caller must ensure lifetime. |
| std::wstring | Yes | Platform wide characters | Size of wchar_t is platform-dependent (Windows 16-bit UTF-16 units; many Unix 32-bit). |
| std::u8string (C++20) | Yes | UTF-8 as char8_t | Strongly-typed UTF-8; interop requires conversion. |
| std::u16string / std::u32string | Yes | UTF-16 / UTF-32 code units | Useful for specific encodings or APIs. |
String Usage
Here's a simple example of creating and concatenating strings:
String Features
Strings support many useful operations such as measuring length, accessing characters, and extracting substrings:
Bounds & Safety
Use operator[] for unchecked access (fast) and at() for checked access (throws on out-of-range):
Non-Owning Views (C++17)
std::string_view lets you pass/read string data without copying. It does not own memory - ensure the referenced data outlives the view.
Encoding & Unicode Note
std::string stores bytes; length()/size() count bytes, not user-perceived characters. With UTF-8, multi-byte code points (e.g., emoji) make size larger than the visible character count. For precise Unicode handling, use appropriate libraries or u8string/u16string/u32string and perform proper conversions.