代码如下:
#include <iostream>
#include <string>
// Function to replace all occurrences of a substring within a string
std::string replaceAll(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);
start_pos += to.length(); // Move past the last replacement to continue searching
}
return str;
}
int main() {
std::string text = "Hello, world! Hello, everyone!";
std::string from = "Hello";
std::string to = "Hi";
std::string result = replaceAll(text, from, to);
std::cout << "Original: " << text << std::endl;
std::cout << "Modified: " << result << std::endl;
return 0;
}
运行结果:
Original: Hello, world! Hello, everyone!
Modified: Hi, world! Hi, everyone!

470

被折叠的 条评论
为什么被折叠?



