samedi 30 mars 2019

Why the program show that the string is out of range?

I'm doing homework about removing some words from the string. It always shows that the string is out of range and I do not know what's wrong with my code.

There are the strings that I use to test my function:

  • "The house whirled around two or three times and rose slowly"
  • "through the air. Dorothy felt as if she were going up in a balloon."
  • "The north and south winds met where the house stood, and made it the"
  • "exact center of the cyclone."

and the following is the words that I have to remove from the above strings:

  • a
  • an
  • A
  • and
  • The
  • the
  • in
  • or
  • of

The program works well for the first two lines, but it shows that it is out of range for the third line, I think that is because I have to remove the last word from the third line (i.e. "the").

int RemoveWordFromLine(string &line, string word)
{
  int no_of_occurence=0;
  int const length_of_stopword=word.length();
 int  const length_of_line=line.length();

 for(int j=0 ;j<=length_of_line-length_of_stopword;j++){

   if (j==0){
   if(line.substr(j,length_of_stopword)==word){

       line.replace(j,length_of_stopword," ");
       no_of_occurence++;
  }
}
if ((j-1>=0) && (j+length_of_stopword<length_of_line)){
  if ((line.substr(j-1,1)==" ") && (line.substr(j+length_of_stopword,1)==" ")){//I have to check this to ensure 'a' in "air" is not removed by the function.
    if(line.substr(j,length_of_stopword)==word){

      line.replace(j,length_of_stopword," ");
      no_of_occurence++;
 }

  }
}

Aucun commentaire:

Enregistrer un commentaire