在C++中替换字符串中出现的所有子字符串,可以使用标准库中的std::string
类及其成员函数。下面是一个示例代码,展示了如何实现这一功能:
#include <iostream>
#include <string>
std::string replaceAll(const std::string& str, const std::string& from, const std::string& to) {
std::string result = str;
size_t start_pos = 0;
while((start_pos = result.find(from, start_pos)) != std::string::npos) {
result.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
return result;
}
int main() {
std::string text = "Hello world, world is beautiful.";
std::string from = "world";
std::string to = "universe";
std::string replacedText = replaceAll(text, from, to);
std::cout << "Original text: " << text << std::endl;
std::cout << "Replaced text: " << replacedText << std::endl;
return 0;
}
通过上述代码和解释,你应该能够理解如何在C++中替换字符串中出现的所有子字符串,并解决可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云