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 ⭐)

TEXT 📖 Display only
string.erase(startPos, deleteCount);

Output:

TEXT 📖 Display only
(program output)

Example:

CPP
#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:

TEXT 📖 Display only
string.insert(insertion position, string to insert);

Example:

CPP
#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)

CPP
#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

CPP
#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:

💡 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)

CPP
#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:

CPP
#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

CPP
#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;
}
CPP
#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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
part1: 
part2: 
part3: 

❓ FAQ

Q Why should I use size_t instead of int when iterating over a string?
A Because string::length() returns size_t (an unsigned integer). Using int may produce warnings when comparing (signed vs. unsigned).
Q What happens when stoi conversion fails?
A It throws a std::invalid_argument exception.

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Write a program that lets the user input a string, then removes all spaces from it.
TEXT 📖 Display only
Input: Hello World, this is C++!
Output: HelloWorld,thisisC++!
  1. 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").

  2. Hint: You can use two pointers (or indices), one moving forward and one moving backward, comparing characters one by one.

  3. Challenge (Difficulty ⭐⭐⭐): Write a program that implements "simple encryption/decryption":

  4. Encryption rule: add 3 to each character's ASCII code (e.g. 'A''D')

  5. Decryption rule: subtract 3 from each character's ASCII code

  6. Let the user input a string, encrypt it, then decrypt it, and output the result


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!

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏