Search code examples
c++stringerase

How to erase characters in a string?


I've got problem with erase function from string. I can't remove a single character from certain index. Maybe I can't use int "i" as iterator ? I want to remove some characters.

#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;

}

My error:

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

Solution

  • In the beginning, the size of tmp is equal to the size of inputText which is a.

    But as soon as you erase a character from tmp, its size decreases by one, and becomes a-1, and if you erase second time, its size would become a-2 and so on. So it is possible that at some point, you will pass an index greater than or equal to the size of tmp, to the erase function, which results in std::out_of_range exception which you don't handle and so your application crashes.