在 C++ 中,你可以使用 std::string 类的成员函数 find() 和 replace() 来实现字符串的查找和替换。下面是一个简单的示例:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string to_find = "World";
std::string to_replace = "C++";
size_t pos = str.find(to_find);
if (pos != std::string::npos) {
str.replace(pos, to_find.length(), to_replace);
}
std::cout << "Original string: " << str << std::endl;
std::cout << "Modified string: " << str << std::endl;
return 0;
}
在这个示例中,我们首先定义了一个原始字符串 str,以及要查找的子字符串 to_find 和要替换的子字符串 to_replace。然后,我们使用 find() 函数查找子字符串 to_find 在原始字符串中的位置。如果找到了(即 pos 不等于 std::string::npos),我们就使用 replace() 函数将子字符串 to_find 替换为子字符串 to_replace。
最后,我们输出原始字符串和修改后的字符串。