String Data Types
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:
#include <string>
#include <iostream>
int main() {
std::string greeting = "Hello";
std::string name = "World";
std::cout << greeting + ", " + name + "!";
return 0;
}
Hello, World!
String Features
Strings support many useful operations such as measuring length, accessing characters, and extracting substrings:
#include <string>
#include <iostream>
int main() {
std::string text = "C++ Programming";
std::cout << "Length: " << text.length() << '\n';
std::cout << "First character: " << text[0] << '\n';
std::cout << "Substring: " << text.substr(0, 3);
return 0;
}
Length: 15 First character: C Substring: C++
Bounds & Safety
Use operator[]
for unchecked access (fast) and at()
for checked access (throws on out-of-range):
#include <string>
#include <iostream>
int main() {
std::string s = "Hi";
std::cout << s[1] << '\n'; // 'i' (unchecked)
try {
std::cout << s.at(5) << '\n'; // throws std::out_of_range
} catch (const std::out_of_range& e) {
std::cout << "out_of_range: " << e.what() << '\n';
}
}
i out_of_range: basic_string::at: __n (which is 5) >= this->size() (which is 2)
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.
#include <string>
#include <string_view>
#include <iostream>
void print_title(std::string_view sv) {
std::cout << sv << '\n';
}
int main() {
std::string title = "C++ String Guide";
print_title(title); // ok: view of std::string
print_title("Temporary literal"); // ok: view of literal with static storage
}
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.