C++

Strings & string_view

11 question(s)

What is std::string and how does it differ from a C-string?

Beginner
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++.
std::string s = "hello";
s += " world";      // grows automatically
const char* c = "hi";  // C-string, manual
Real-world example Using std::string avoids buffer-overflow bugs common with fixed char[] buffers.

Common follow-ups: Who manages std::string's memory? | Why is std::string safer than char[]?

Memory Management STL Strings & string_view

What is std::string_view and why was it added?

Beginner
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.

Common follow-ups: Does string_view own its data? | Why use it for parameters?

Strings & string_view References & Pointers Strings & string_view

What are the dangers of std::string_view?

Intermediate
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.

Common follow-ups: Why can a string_view dangle? | Is string_view null-terminated?

Memory Management Strings & string_view Strings & string_view

How does std::string manage memory and what is SSO?

Intermediate
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.

Common follow-ups: What is Small String Optimization? | When does a string use the heap?

Memory Management Strings & string_view Strings & string_view

How do you convert between std::string and numbers?

Beginner
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.

Common follow-ups: What does stoi do on invalid input? | Why prefer from_chars for performance?

Strings & string_view STL Strings & string_view

What is the difference between passing const std::string& and std::string_view?

Advanced
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.

Common follow-ups: Why can const std::string& cause a temporary? | When keep const std::string&?

Strings & string_view References & Pointers Strings & string_view

How do you efficiently build up a large string?

Intermediate
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.

Common follow-ups: Why does reserve help? | What does ostringstream offer?

I/O Streams Memory Management Strings & string_view

What is std::format (C++20) and how does it improve string formatting?

Advanced
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.

Common follow-ups: Why is std::format safer than printf? | How do you format custom types?

Modern C++ Strings & string_view Strings & string_view

What common operations does std::string provide?

Beginner
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.

Common follow-ups: What is the difference between [] and at()? | What does c_str() return?

STL Strings & string_view Strings & string_view

How do you handle Unicode and encodings in C++ strings?

Advanced
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.

Common follow-ups: Does size() count characters or bytes? | When do you need a Unicode library?

Strings & string_view Modern C++ Strings & string_view