std::string owns a sequence of characters with dynamic size—replacing manual char* buffer management from C strings in most C++ code.
Basics
std::string greeting = "Hello";
greeting += ", C++";
std::cout << greeting.size() << "\n";
Use .c_str() or .data() when passing to C APIs expecting null-terminated strings.
Important interview questions and answers
- Q: string vs string_view?
A:std::string_view(C++17) is non-owning reference to characters—great for read-only parameters. - Q: Small String Optimization?
A: Many implementations store short strings inline without heap allocation.
Self-check
- How do you concatenate strings?
- When use c_str()?
Tip: std::string manages memory—unlike C strings, you rarely need manual buffer sizing for typical text.
Interview prep
- string vs char*?
std::stringowns dynamic data with RAII;char*requires manual lifetime management.- string_view?
Non-owning view of characters—great for read-only parameters without copying.