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

c++
607
2023/10/18 20:35:13
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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字符都被替换为*字符。

希望对你有所帮助!

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C++软件架构是什么