How to Replace Text in a String in C++
In C++, you can replace part of a string using the
std::string::replace method by specifying the start position, length of the part to replace, and the new string. Alternatively, you can use std::regex_replace for pattern-based replacements.Syntax
The std::string::replace method replaces a portion of the string starting at a given position and spanning a given length with another string.
pos: The starting index where replacement begins.len: The number of characters to replace.str: The new string to insert.
cpp
string& replace (size_t pos, size_t len, const string& str);
Example
This example shows how to replace a word inside a string using replace. It replaces "world" with "C++".
cpp
#include <iostream> #include <string> int main() { std::string text = "Hello world!"; size_t pos = text.find("world"); if (pos != std::string::npos) { text.replace(pos, 5, "C++"); } std::cout << text << std::endl; return 0; }
Output
Hello C++!
Common Pitfalls
Common mistakes include:
- Not checking if the substring exists before replacing, which can cause unexpected behavior.
- Using incorrect positions or lengths that go beyond the string size.
- Confusing
replacewithreplace_allwhich does not exist instd::string.
cpp
#include <iostream> #include <string> int main() { std::string text = "Hello world!"; // Wrong: not checking if "planet" exists size_t pos = text.find("planet"); // This will replace from npos which is invalid if (pos != std::string::npos) { text.replace(pos, 6, "Earth"); } else { std::cout << "Substring not found, no replacement done." << std::endl; } std::cout << text << std::endl; return 0; }
Output
Substring not found, no replacement done.
Hello world!
Quick Reference
| Method | Description | Example Usage |
|---|---|---|
| std::string::replace | Replace part of string by position and length | text.replace(pos, len, "new") |
| std::string::find | Find substring position | pos = text.find("old") |
| std::regex_replace | Replace using pattern matching (requires | std::regex_replace(text, std::regex("old"), "new") |
Key Takeaways
Use std::string::replace with position and length to replace parts of a string.
Always check if the substring exists using find() before replacing.
Avoid out-of-range positions to prevent runtime errors.
For pattern-based replacements, use std::regex_replace from .
std::string::replace replaces only one part; loop or regex needed for multiple replacements.