-1

我对字符串中的擦除功能有问题。我无法从某个索引中删除单个字符。也许我不能使用 int "i" 作为迭代器?我想删除一些字符。

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

void deleteChars(string inputText, string inputChars);

int main(int argc, char *argv[])
{
    string tekst1 = ("mama fama lilo babo sabo");
    string tekst2 = ("mabo");

    deleteChars(tekst1, tekst2);

    system("PAUSE");
    return EXIT_SUCCESS;
}

void deleteChars(string inputText, string inputChars){
          int a = inputText.size();
          int b = inputChars.size();

          string tmp = inputText;

          for(int i=0; i<a; i++){
                  for(int j=0; j<b; j++){
                          if(inputText.at(i)==inputChars.at(j)){
                              tmp.erase(i,1);  //Here is my problem ?
                           }                                    
                  }
          }

          inputText = tmp;

          cout<<"text: "<<inputText<<endl;

}

我的错误:

This application has requested the Runtime to terminate it in an unusual way
4

2 回答 2

12

在你从位置 5 删除一个字符后,位置 6 的字符移动到位置 5,字符串长度减一。如果您稍后尝试擦除 的最后一个字符tmp,它将引发异常,因为tmp它已经比您预期的短一个字符。向后迭代字符串以避免这种情况。

于 2012-04-11T17:57:25.533 回答
4

一开始, 的大小tmp等于 的inputText大小a

但是一旦你从 中删除一个字符tmp,它的大小就会减一,变成a-1,如果你第二次删除,它的大小就会变成a-2等等。因此,在某些时候,您可能会将大于或等于 , 大小的索引传递tmperase函数,这会导致std::out_of_range您无法处理的异常,从而导致您的应用程序崩溃。

于 2012-04-11T17:59:30.287 回答