c++ 字符串替换replace函数

时间:2025-03-15 07:15:27

      由于c++中的replace函数只能替换一次字符串中的字符/子串,所有需要通过循环遍历方式,多次替换。根据循环方法不同,分为以下几个方法:

方法1:通过size_type pos 指针 加上简单的while(true)循环进行遍历

string::size_type pos(0);

while (true)
{

pos = modi_reason.find(“ ”);

if( pos != string::npos )

{

modi_reason.replace(pos , 1 , “” );

}

else

{

    break;

}

}

方法2,(同方法1)

while(true)

{

        string::iterator p = find( old_string.begin(), old_string.end(), 'new_char' );

        if ( p!= old_string.end() )

        {

           old_string.replace( p , old_sub_string.length() ,  new_sub_string )

        }

}

方法3:通过size_type pos 指针进行遍历

string& replace_all(string& src, const string& old_value, const string& new_value) {
    // 每次重新定位起始位置pos += new_value.length(),

    //并重新从新的起始位置pos进行find , (old_value, pos)

    //防止上轮替换后的字符串形成新的old_value
    for (string::size_type pos(0); pos != string::npos; pos += new_value.length()) {
        if ((pos = (old_value, pos)) != string::npos) {
            (pos, old_value.length(), new_value);
        }
        else break;   //已经找不到需要替换的字符串了,break掉。
    }
    return src;
}

方法4:通过迭代器进行遍历(适用于单个字符的替换)

string::iterator  itor = old_string.begin();

for( ; itor !=  old_string.end(); itor++)

{

     if(strcmp( (*itor).c_str() , old_char ) ==0 )

    {

         old_string.replace( itor ,  1 ,  new_char );

    }

}