C++ string replacement function based on the use of details

  • 2020-04-01 23:39:03
  • OfStack

In C++, there are many methods for string replacement. Here I mainly talk about the replacement in WString in STL. Although WString comes with a Replace function, it can only be replaced once
[function]

 
        static wstring Replace(const wstring& orignStr, const wstring& oldStr, const wstring& newStr);

[implementation]

std::wstring Replace( const wstring& orignStr, const wstring& oldStr, const wstring& newStr ) 
{ 
    size_t pos = 0; 
    wstring tempStr = orignStr; 
    wstring::size_type newStrLen = newStr.length(); 
    wstring::size_type oldStrLen = oldStr.length(); 
    while(true) 
    { 
        pos = tempStr.find(oldStr, pos); 
        if (pos == wstring::npos) break; 
        tempStr.replace(pos, oldStrLen, newStr);         
        pos += newStrLen;
    } 
    return tempStr; 
}


Related articles: