How to replace all occurrences of a character in string?

后端 未结 15 1285
别那么骄傲
别那么骄傲 2020-11-22 05:54

What is the effective way to replace all occurrences of a character with another character in std::string?

15条回答
  •  悲&欢浪女
    2020-11-22 06:19

    #include 
    #include 
    using namespace std;
    // Replace function..
    string replace(string word, string target, string replacement){
        int len, loop=0;
        string nword="", let;
        len=word.length();
        len--;
        while(loop<=len){
            let=word.substr(loop, 1);
            if(let==target){
                nword=nword+replacement;
            }else{
                nword=nword+let;
            }
            loop++;
        }
        return nword;
    
    }
    //Main..
    int main() {
      string word;
      cout<<"Enter Word: ";
      cin>>word;
      cout<

提交回复
热议问题