std::string s = "hello";
s += " world"; // grows automatically
const char* c = "hi"; // C-string, manual
C++
Topics in this category
Casting & Conversions
Compilation & Linking
Concepts & Constraints
Concurrency
Const Correctness
Constexpr & Compile-Time
Coroutines
Enums & Enum Classes
Exception Handling
I/O Streams
Lambda Expressions
Memory Management
Modern C++
Move Semantics
Namespaces
OOP & Classes
Operator Overloading
Preprocessor & Macros
RAII & Smart Pointers
Ranges & Views
C++
Strings & string_view
std::string is a class that owns and manages a dynamically-sized sequence of characters, handling memory automatically, growth, and many operations (concatenation, search, substr). A C-string is a raw null-terminated char array with manual memory management and no bounds safety. std::string is the safe, convenient default in C++.
Real-world example
Using std::string avoids buffer-overflow bugs common with fixed char[] buffers.
Memory Management
STL
Strings & string_view
std::string_view (C++17) is a non-owning, read-only view over a contiguous sequence of characters (a pointer plus length). It avoids copying when you only need to read a string, and can refer to std::string, C-strings, or substrings uniformly. It's ideal for function parameters that just inspect text.
void log(std::string_view msg); // no copy for any string type
log("literal"); log(myString);
Real-world example
Changing a parameter from const std::string& to string_view lets callers pass literals without constructing a string.
Strings & string_view
References & Pointers
Strings & string_view
Because string_view doesn't own its data, it dangles if the underlying string is destroyed or modified (e.g., a view of a temporary, or of a std::string that reallocates). You must ensure the referenced data outlives the view. Also, string_view isn't guaranteed null-terminated, so don't pass its data() to C APIs expecting a null terminator.
std::string_view v = std::string("temp"); // dangles: temporary destroyed
Real-world example
A string_view returned from a function referencing a local string dangles and reads freed memory.
Memory Management
Strings & string_view
Strings & string_view
std::string allocates a heap buffer for its characters and grows it as needed (amortized, like vector). Most implementations use Small String Optimization (SSO): short strings are stored inline in the object itself, avoiding heap allocation entirely, which speeds up common short-string usage. Larger strings spill to the heap.
std::string s = "hi"; // likely stored inline (SSO), no heap alloc
Real-world example
Short identifiers benefit from SSO, avoiding heap allocations in hot string-heavy code.
Memory Management
Strings & string_view
Strings & string_view
Use std::to_string(n) to convert numbers to strings, and std::stoi/std::stol/std::stod etc. to parse strings to numbers. C++17 adds std::from_chars/std::to_chars for fast, locale-independent, non-throwing conversions ideal for performance-critical parsing.
std::string s = std::to_string(42);
int n = std::stoi("123");
// fast: std::from_chars(begin, end, value);
Real-world example
A CSV parser uses std::from_chars for fast, allocation-free numeric parsing.
Strings & string_view
STL
Strings & string_view
const std::string& avoids a copy but forces the caller to have (or construct) a std::string—a string literal creates a temporary std::string. std::string_view accepts any character source (literal, std::string, substring) without constructing a string, and is cheap to copy. Prefer string_view for read-only parameters, unless you need a null-terminated string or to store it.
void a(const std::string& s); // literal -> temp std::string
void b(std::string_view s); // literal -> no allocation
Real-world example
Switching read-only APIs to string_view removes hidden std::string temporaries from literal arguments.
Strings & string_view
References & Pointers
Strings & string_view
Repeated + concatenation can cause many reallocations. Efficient approaches: reserve() the expected capacity up front, use += (append in place), use a std::ostringstream for formatted assembly, or std::string::append. Reserving capacity avoids repeated growth-and-copy, which dominates naive concatenation performance.
std::string s;
s.reserve(1000); // avoid reallocations
for (auto& part : parts) s += part;
Real-world example
Reserving capacity before a build loop turns O(n^2) reallocation into a single allocation.
I/O Streams
Memory Management
Strings & string_view
std::format provides Python-style, type-safe, positional string formatting that returns a std::string, replacing error-prone printf (no format/argument mismatches) and verbose iostream manipulators. It's extensible for user types via formatter specializations and is generally faster and safer than the alternatives.
std::string s = std::format("{} + {} = {}", 2, 3, 5);
Real-world example
Replacing sprintf with std::format removes format-string vulnerabilities and type mismatches.
Modern C++
Strings & string_view
Strings & string_view
std::string offers size()/length(), empty(), indexing with [] or at() (bounds-checked), substr(), find()/rfind(), replace(), append()/+=, comparison operators, c_str() for a null-terminated C-string, and iteration. These cover most text-manipulation needs without manual memory handling.
std::string s = "hello world";
auto pos = s.find("world"); // 6
std::string w = s.substr(pos); // "world"
Real-world example
Parsing a filename uses find and substr to extract the extension safely.
STL
Strings & string_view
Strings & string_view
std::string holds bytes (often UTF-8) with no inherent encoding awareness—size() returns bytes, not characters. C++ has limited built-in Unicode support: char8_t/std::u8string (C++20) mark UTF-8, char16_t/char32_t for UTF-16/32, but proper Unicode processing (normalization, grapheme clusters) usually requires libraries like ICU. Treating std::string as UTF-8 bytes is a common pragmatic approach.
std::u8string s = u8"héllo"; // UTF-8 literal (char8_t)
Real-world example
A text app stores UTF-8 in std::string but uses ICU for correct case-folding and normalization.
Strings & string_view
Modern C++
Strings & string_view