How to find and replace all occurrences of a substring in a string?

前端 未结 7 1493
无人共我
无人共我 2020-12-31 06:49

I need to search a string and edit the formatting of it.

So far I can replace the first occurrence of the string, but I am unable to do so with the next occurrences

7条回答
  •  Happy的楠姐
    2020-12-31 07:04

    /// Returns a version of 'str' where every occurrence of
    /// 'find' is substituted by 'replace'.
    /// - Inspired by James Kanze.
    /// - http://stackoverflow.com/questions/20406744/
    std::string replace_all(
        const std::string & str ,   // where to work
        const std::string & find ,  // substitute 'find'
        const std::string & replace //      by 'replace'
    ) {
        using namespace std;
        string result;
        size_t find_len = find.size();
        size_t pos,from=0;
        while ( string::npos != ( pos=str.find(find,from) ) ) {
            result.append( str, from, pos-from );
            result.append( replace );
            from = pos + find_len;
        }
        result.append( str, from , string::npos );
        return result;
    /*
        This code might be an improvement to James Kanze's
        because it uses std::string methods instead of
        general algorithms [as 'std::search()'].
    */
    }
    
    int main() {
        {
            std::string test    = "*A ... *A ... *A ...";
            std::string changed = "*A\n ... *A\n ... *A\n ...";
    
            assert( changed == replace_all( test, "*A", "*A\n" ) );
        }
        {
            std::string GB = "My gorila ate the banana";
    
            std::string gg = replace_all( GB, "gorila", "banana" );
            assert( gg ==  "My banana ate the banana" );
            gg = replace_all( gg, "banana", "gorila"  );
            assert( gg ==  "My gorila ate the gorila" );
    
            std::string bb = replace_all( GB, "banana", "gorila" );
            assert( gg ==  "My gorila ate the gorila" );
            bb = replace_all( bb, "gorila" , "banana" );
            assert( bb ==  "My banana ate the banana" );
        }
        {
            std::string str, res;
    
            str.assign( "ababaabcd" );
            res = replace_all( str, "ab", "fg");
            assert( res == "fgfgafgcd" );
    
            str="aaaaaaaa"; assert( 8==str.size() );
            res = replace_all( str, "aa", "a" );
            assert( res == "aaaa" );
            assert( "" == replace_all( str, "aa", "" ) );
    
            str = "aaaaaaa"; assert( 7==str.size() );
            res = replace_all( str, "aa", "a" );
            assert( res == "aaaa" );
    
            str = "..aaaaaa.."; assert( 10==str.size() );
            res = replace_all( str, "aa", "a" );
            assert( res == "..aaa.." );
    
            str = "baaaac"; assert( 6==str.size() );
            res = replace_all( str, "aa", "" );
            assert( res == "bc" );
        }
    }
    

提交回复
热议问题