温馨提示×

c++字符串替换指定字符怎么实现

c++
小亿
130
2023-10-18 20:35:13
栏目: 编程语言

在C++中,可以使用std::string类来表示字符串,可以使用std::replace函数来替换字符串中的指定字符。

下面是一个示例代码:

#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "Hello, World!";
char oldChar = 'o';
char newChar = '*';
std::replace(str.begin(), str.end(), oldChar, newChar);
std::cout << str << std::endl;
return 0;
}

在上述代码中,我们定义了一个字符串str,并指定了要替换的字符oldChar和替换后的字符newChar。然后,我们使用std::replace函数来替换字符串中的所有oldChar字符为newChar字符。最后,我们输出替换后的字符串。

运行以上代码会输出Hell*, W*rld!,可以看到字符串中的所有o字符都被替换为*字符。

希望对你有所帮助!

0