【问题标题】:c++ string: is there good way to replace a char inside a stringc ++字符串:有没有好方法来替换字符串中的字符
【发布时间】:2010-09-25 14:22:08
【问题描述】:

我想将字符串中所有出现的 ' 替换为 ^,但我看到 string.replace 不适合我,我需要自己编写吗?很无聊。

【问题讨论】:

    标签: c++ string stl


    【解决方案1】:

    您可以使用来自<algorithm>std::replace,而不是使用来自<string>string::replace

    示例代码

    #include <iostream>
    #include <algorithm>
    
    int main()
    {
       std::string s = "I am a string";
       std::replace(s.begin(),s.end(),' ',',');
       std::cout<< s;
    
    } 
    

    输出:I,am,a,string

    【讨论】:

    • +1 是一个直接的解决方案,让我自定义构建的 STD::replace 函数成为一种浪费。
    猜你喜欢
    • 2010-10-31
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 2012-01-05
    • 2012-09-25
    相关资源
    最近更新 更多