字符串替换函数c ++

时间:2011-10-31 21:55:17

标签: c++ string replace

  

可能重复:
  How to find and replace string?

我如何获得如下功能:

string gg="13332";
gg.replace("333","");//gg="12"

? 我在标准库中找不到任何东西。 编辑:我的功能:

     bool isDalshe=false;
         do{
             isDalshe=false;
         for(int i=0;i<10;i++){
             for(int j=3;j<9;j++){
                 found=sk.find(mas[i][j].ch);
                 if(found!= std::string::npos){
                 glob_c+=mas[i][j].i;
                 cout<<"Found: "<<int(found)<<endl;
//In this place I need to replace "mas[i][j].ch" with "" in sk
                 isDalshe=true;
                 }
             }}
         }
         while(isDalshe);

4 个答案:

答案 0 :(得分:3)

答案 1 :(得分:2)

std::stringreplace方法,与您正在寻找的方法很接近。

我应该这样做,我想:

std::string gg="13332";
gg.replace(1, 3, "");//gg="12"

但更好的是,请使用Boost:Here。 Boos可以在一次调用中进行查找和替换,包括多次替换,使用std::string方法进行手动操作。

答案 2 :(得分:2)

std::string中的所有替换形式都占据了位置,因此您必须找到现有的字符串,并将其替换为新的字符串作为两个单独的步骤,如下所示:

while ((pos=gg.find("333")) != std::string::npos)
    gg.replace(pos, 3, "");

另一种选择是将您的字符串视为一个集合,并在其上使用std::replace。但是,这实际上是为了替换元素元素,因此对于您的任务,它将无法正常工作。如果你真的想要从字符串中删除所有a,你可以使用std::remove,但是如果(例如)你想将“133323”变成“123”则不行“(它会删除所有 3 s,无法告诉你只想删除连续三个'3'的字符串。

答案 3 :(得分:1)

也许这会有所帮助: Segmentation error while replacing substrings of a string with other substring

[因为帖子下面有一个C标签]