代码改变世界

c++ string 替换

2012-06-15 00:55  youxin  阅读(2528)  评论(0编辑  收藏  举报

 可以用string的成员函数replace 或 算法库里的replace函数

string& replace ( size_t pos1, size_t n1,   const string& str );
还有很多的函数参数形式。
replace之前可以用string 成员函数find找到你想替换的字符串

string::find

size_t find ( const string& str, size_t pos = 0 ) const;
size_t find ( const char* s, size_t pos, size_t n ) const;
size_t find ( const char* s, size_t pos = 0 ) const;
size_t find ( char c, size_t pos = 0 ) const;

string  str="hello-world";
    int foundPos=str.find('-',0);
    if(foundPos!=string::npos)
        str.replace(foundPos,1,"   ");
    cout<<str<<endl;

会替换-为两个空格。上面的代码只能替换第一次出现的字符,对于多个,可以用循环,或直接用stl的replace。

 

直接用stl的replace;

template < class ForwardIterator, class T >
  void replace ( ForwardIterator first, ForwardIterator last,
                 const T& old_value, const T& new_value );


string str="hello-world-welcome-to-masm";
  
    replace(str.begin(),str.end(),'-',' ');
    cout<<str<<endl;

注意str.begin()所指类型应和后面的两个参数类型一致,如果写成以下几种形式;

replace(str.begin(),str.end(),"-"," ");
replace(str.begin(),str.end(),'-'," ");

都是不行的。因为str.begin()所指的是字符。所以只能用字符来替换。

  stl的replace会替换所有出现的目标字符