What is std::string and common string operations?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
std::string is C++'s managed string class — automatically handles memory. Always prefer over C-style char* strings. Creation: std::string s1 = "hello"; std::string s2("world"); std::string s3(5, '*'); // "*****" std::string s4 = s1 + " " + s2; // "hello world". Common operations: // Size and access: s1.size() / s1.length(); // 5 s1.empty(); // false s1[0]; // 'h' -- no bounds check s1.at(0); // 'h' -- bounds checked (throws) s1.front(); s1.back(); // Modifying: s1 += " there"; // Append s1.append(" more"); s1.push_back('!'); s1.insert(5, " new"); // Insert at position s1.erase(5, 4); // Erase 4 chars from pos 5 s1.replace(0, 5, "hi"); // Replace range with new string s1.clear(); // Searching: s1.find("world"); // Position or string::npos s1.rfind("o"); // From right s1.find_first_of("aeiou"); // First vowel // Substrings: s1.substr(6, 5); // 5 chars starting at pos 6 // Comparison: s1 == s2; s1 < s2; s1.compare(s2); // -1, 0, 1 // Conversion: int n = std::stoi("42"); double d = std::stod("3.14"); std::string str = std::to_string(42); // std::string_view (C++17) -- non-owning reference: std::string_view sv = s1; // No copy -- just a view. std::string vs const char*: string manages its own memory (safe), supports all operations, can be empty. Use string_view for read-only string parameters — avoids copies. SSO (Small String Optimization): short strings (typically <15-23 chars) are stored inline within the string object — no heap allocation, very fast.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your C++ experience.
Previous
What are abstract classes and interfaces in C++?
Next
What are function pointers and std::function in C++?