温馨提示×

c++ string怎么替换某字符为其他字符

c++
小亿
404
2024-08-17 11:13:34
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要替换C++中的字符串中的某个字符为另一个字符,可以使用std::replace函数。

以下是一个简单的示例代码:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string str = "Hello, World!";
    
    // 将字符串中的逗号(,)替换为感叹号(!)
    std::replace(str.begin(), str.end(), ',', '!');

    std::cout << str << std::endl;

    return 0;
}

在上面的示例中,我们使用std::replace函数将字符串str中的逗号,替换为感叹号!。您可以根据需要替换任何字符。

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

推荐阅读:c++ replace函数效率如何

0