C++: Advanced String Manipulation
Last updated: 2026-08-26
In lesson 19 we learned the basics of string operations.
But in real-world scenarios, you may need to delete characters, insert characters, compare strings, convert numbers to strings...
In this lesson, we'll learn advanced string operations.
1. Modifying Strings
(1) 1.1 Deleting Characters (erase)
Syntax:
▶ Example 2: Code Example (Difficulty ⭐)
string.erase(startPos, deleteCount);
Output:
(program output)
Example:
#include <iostream>
#include <string>
int main() {
std::string text = "Hello, World!";
// Delete 7 characters starting from position 5 (", World")
text.erase(5, 7);
std::cout << text << std::endl; // Hello!
return 0;
}
💡 Tip: If you pass only one argument, erase(pos) deletes all characters from pos to the end.
(2) 1.2 Inserting Characters (insert)
Syntax:
string.insert(insertion position, string to insert);
Example:
#include <iostream>
#include <string>
int main() {
std::string text = "Hello!";
// Insert " World" before the 5th character
text.insert(5, " World");
std::cout << text << std::endl; // Hello World!
return 0;
}
(3) 1.3 Clearing a String (clear)
#include <iostream>
#include <string>
int main() {
std::string text = "Hello";
text.clear(); // Clear the string
std::cout << "Length: " << text.length() << std::endl; // 0
std::cout << "Is empty: " << text.empty() << std::endl; // 1 (true)
return 0;
}
💡 Tip: The empty() function checks whether a string is empty (returns true, i.e. 1, if empty).
2. Comparing Strings (compare)
Although you can compare strings using ==, !=, <, >, the compare() function provides more detailed information.
(1) 2.1 Basic Usage
#include <iostream>
#include <string>
int main() {
std::string s1 = "apple";
std::string s2 = "banana";
int result = s1.compare(s2);
if (result == 0) {
std::cout << "s1 equals s2" << std::endl;
} else if (result < 0) {
std::cout << "s1 is less than s2" << std::endl; // This line executes
} else {
std::cout << "s1 is greater than s2" << std::endl;
}
return 0;
}
Return values:
0: the two strings are equal< 0: the caller is less than the argument> 0: the caller is greater than the argument
💡 Tip: In practice, using ==, !=, <, > directly to compare strings is more intuitive — these operators are recommended.
3. Converting Between Strings and Numbers
(1) 3.1 Numbers to Strings (to_string)
#include <iostream>
#include <string>
int main() {
int age = 25;
double price = 19.99;
std::string ageStr = std::to_string(age);
std::string priceStr = std::to_string(price);
std::cout << "Age: " << ageStr << std::endl;
std::cout << "Price: " << priceStr << std::endl;
return 0;
}
💡 Tip: to_string() preserves 6 decimal places when converting floating-point numbers. If you need to control the format, use std::ostringstream or std::format (C++20).
(2) 3.2 Strings to Numbers (stoi, stod)
| Function | Purpose | Example |
|---|---|---|
std::stoi(str) |
String → int | int x = std::stoi("123"); |
std::stol(str) |
String → long | long x = std::stol("123"); |
std::stoll(str) |
String → long long | long long x = std::stoll("123"); |
std::stof(str) |
String → float | float x = std::stof("3.14"); |
std::stod(str) |
String → double | double x = std::stod("3.14"); |
Example:
#include <iostream>
#include <string>
int main() {
std::string numStr = "123";
std::string priceStr = "19.99";
int num = std::stoi(numStr);
double price = std::stod(priceStr);
std::cout << "num = " << num << std::endl;
std::cout << "price = " << price << std::endl;
return 0;
}
⚠️ Note: If the string is not a valid number format, stoi / stod will throw an exception. We'll learn how to handle this with try-catch later.
4. Iterating Over Strings
(1) 4.1 Using Subscripts
#include <iostream>
#include <string>
int main() {
std::string text = "Hello";
for (size_t i = 0; i < text.length(); i++) {
std::cout << text[i] << " ";
}
std::cout << std::endl;
return 0;
}
(2) 4.2 Using Range-based for (C++11, Recommended)
#include <iostream>
#include <string>
int main() {
std::string text = "Hello";
for (char c : text) {
std::cout << c << " ";
}
std::cout << std::endl;
return 0;
}
💡 Tip: Range-based for is more concise and less prone to loop condition errors.
5. Practice: Simple Text Editor
▶ Example 1: Implementing "Find and Replace" (Difficulty ⭐⭐)
#include <iostream>
#include <string>
int main() {
std::string text = "I like C. C is powerful.";
std::string oldStr = "C";
std::string newStr = "C++";
size_t pos = 0;
while ((pos = text.find(oldStr, pos)) != std::string::npos) {
text.replace(pos, oldStr.length(), newStr);
pos += newStr.length(); // Avoid infinite loop
}
std::cout << "After replacement: " << text << std::endl;
return 0;
}
Output:
After replacement:
💡 Key point: After replacing, skip past the newly inserted string; otherwise you'll get an infinite loop (if the new string contains the old string).
▶ Example 3: Extracting Substrings with substr (Difficulty ⭐)
#include <iostream>
#include <string>
int main() {
std::string text = "Hello, C++ World!";
// Extract "Hello"
std::string part1 = text.substr(0, 5);
std::cout << "part1: " << part1 << std::endl;
// Extract "C++"
std::string part2 = text.substr(7, 3);
std::cout << "part2: " << part2 << std::endl;
// Extract from position 7 to the end
std::string part3 = text.substr(7);
std::cout << "part3: " << part3 << std::endl;
return 0;
}
Output:
part1:
part2:
part3:
❓ FAQ
size_t instead of int when iterating over a string?string::length() returns size_t (an unsigned integer). Using int may produce warnings when comparing (signed vs. unsigned).stoi conversion fails?std::invalid_argument exception.📖 Summary
erase()deletes characters,insert()inserts characters,clear()clears the stringcompare()compares strings (but using==,!=etc. is recommended)to_string()converts numbers to stringsstoi()/stod()converts strings to numbers- Range-based
foris recommended for iterating over strings (C++11)
📝 Exercises
- Basic (Difficulty ⭐): Write a program that lets the user input a string, then removes all spaces from it.
Input: Hello World, this is C++!
Output: HelloWorld,thisisC++!
-
Intermediate (Difficulty ⭐⭐): Write a program that lets the user input a string and determines whether it is a "palindrome" (reads the same forwards and backwards, e.g. "level", "radar").
-
Hint: You can use two pointers (or indices), one moving forward and one moving backward, comparing characters one by one.
-
Challenge (Difficulty ⭐⭐⭐): Write a program that implements "simple encryption/decryption":
-
Encryption rule: add 3 to each character's ASCII code (e.g.
'A'→'D') -
Decryption rule: subtract 3 from each character's ASCII code
-
Let the user input a string, encrypt it, then decrypt it, and output the result
- Searching: find/rfind/find_first_of to locate substrings
- Extracting: substr(pos, count) to extract substrings
- Replacing: replace(pos, count, str) to replace portions
- Inserting/Deleting: insert/erase to dynamically modify strings
- Type conversion: stoi/stod/to_string to convert between strings and numbers
6. 🚀 Next Steps
Now that you've learned advanced string operations, we'll move on to Phase 4 (Pointers and References) — the most "intimidating" but also most important part of C++. Understanding memory is key to writing efficient code!