Search code examples
c++algorithmstr-replacestdstring

To replace one char by a higher amount of chars within a string, without deleting other letters in C++


I want to replace character 'ü' in a string if found in it. My code replaces ü, but also deleting other letters in the string.

 if (word.find('ü') != string::npos) 
 {
     word.replace(word.find('ü'), 'ü', "ue");
 }

Solution

  • You can find the position of ü, starting from index 0 until end of the string and whenever you find, replace it with ue using the information of both position where you found and the length of the string you would like to find in the given string.

    Something like follows: SEE LIVE HERE

    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <cstddef>
    
    int main()
    {
       std::string word("Herr Müller ist ein König.");
    
       std::string findThis = "ü";
       std::string replaceWith = "ue";
    
       std::size_t pos = 0;
       while ((pos = word.find(findThis, pos)) != std::string::npos)
       {
          word.replace(pos, findThis.length(), replaceWith);
          pos += replaceWith.length();
       }
    
       std::cout << word << std::endl;
       return 0;
    }
    

    Output:

    Herr Mueller ist ein König.