Replacing all occurrences of a substring within a std::string
is a common operation in text processing. While C++ doesn't have a built-in replace_all()
function, we can implement one efficiently. Here's a robust approach:
#include <iostream>
#include <string>
std::string replace_all(
std::string str,
const std::string& from,
const std::string& to
) {
size_t start_pos{0};
while (
(start_pos = str.find(from, start_pos))
!= std::string::npos
) {
str.replace(start_pos, from.length(), to);
// In case 'to' contains 'from', like
// replacing 'x' with 'yx'
start_pos += to.length();
}
return str;
}
int main() {
std::string text{
"The quick brown fox jumps over the lazy dog"};
std::string from{"o"};
std::string to{"0"};
std::cout << "Original: " << text << '\n';
std::cout << "Replaced: "
<< replace_all(text, from, to) << '\n';
// Another example
text = "Hello, Hello, Hello!";
from = "Hello";
to = "Hi";
std::cout << "Original: " << text << '\n';
std::cout << "Replaced: "
<< replace_all(text, from, to) << '\n';
}
Original: The quick brown fox jumps over the lazy dog
Replaced: The quick br0wn f0x jumps 0ver the lazy d0g
Original: Hello, Hello, Hello!
Replaced: Hi, Hi, Hi!
Let's break down the replace_all()
 function:
std::string::find()
to locate each occurrence of the from
substring.std::string::replace()
.start_pos
to continue searching after the replaced substring.This approach is efficient because:
std::string
's built-in methods, which are typically optimized.For more complex pattern matching and replacing, you might consider using regular expressions:
#include <regex>
std::string regex_replace_all(
const std::string& str,
const std::string& from,
const std::string& to
) {
return std::regex_replace(
str, std::regex(from), to
);
}
However, be aware that regex operations can be slower for simple replacements. Use them when you need more complex pattern matching capabilities.
For very large strings or performance-critical code, you might want to consider using a more sophisticated string searching algorithm like Boyer-Moore or Knuth-Morris-Pratt. These can be more efficient for long strings or when doing many replacements.
Remember, the most appropriate method depends on your specific use case, including the size of your strings, the complexity of your patterns, and your performance requirements.
Answers to questions are automatically generated and may not have been reviewed.
std::string
ClassA detailed guide to std::string
, covering the most essential methods and operators