String Operations

Common string manipulations

Interview Relevant: Very common in interviews

String Operations

Essential string manipulation techniques for interviews.

Code Examples

Advanced string manipulation techniques.

cpp
1string s = "Hello World";
2
3// Modify
4s.insert(5, "!!!");         // "Hello!!! World"
5s.erase(5, 3);              // "Hello World"
6s.replace(0, 5, "Hi");      // "Hi World"
7
8// Convert case
9transform(s.begin(), s.end(), s.begin(), ::tolower);
10transform(s.begin(), s.end(), s.begin(), ::toupper);
11
12// Split string (no built-in, use stringstream)
13stringstream ss("one two three");
14string word;
15vector<string> words;
16while (ss >> word) {
17    words.push_back(word);
18}
19
20// Join (C++20 or manual)
21string joined;
22for (int i = 0; i < words.size(); i++) {
23    if (i > 0) joined += ",";
24    joined += words[i];
25}
26
27// Trim whitespace
28s.erase(0, s.find_first_not_of(" \t\n"));
29s.erase(s.find_last_not_of(" \t\n") + 1);
30
31// Reverse
32reverse(s.begin(), s.end());
33
34// Convert to/from numbers
35int num = stoi("42");
36double d = stod("3.14");
37string str = to_string(42);

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In