为什么程序显示字符串超出范围

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

本文关键字:范围 字符串 程序 显示 为什么      更新时间:2023-10-16

我正在做关于从字符串中删除一些单词的功课。它总是显示字符串超出范围,我不知道我的代码出了什么问题。

有我用来测试我的函数的字符串:

  • "房子转了两三圈,慢慢升起">
  • "通过空气。多萝西觉得自己好像在气球上飞起来。
  • "南北风在房子所在的地方相遇,并使其成为">
  • "正是旋风的中心。">

以下是我必须从上述字符串中删除的单词:

  • 一个
  • 一个

该程序在前两行运行良好,但它表明它超出了第三行的范围,我认为这是因为我必须从第三行中删除最后一个单词(即"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++;
 }
  }
}

删除单词时,字符串的长度会减小。但是您仍然循环到字符串的原始长度。一个简单的解决方法是摆脱length_of_line,只需在需要长度的任何地方调用line.length()

正如 David 的回答所解释的那样,您需要动态检查line.length()以考虑行字符串的转换。这解释了超出范围的原因。

然而,这里还有另外两个问题。

第一种是当停用词位于行尾,后面没有任何空格时。 这种情况目前会错过。

第二种是当一行以停用词的字符序列开头,但以空格以外的其他内容继续(例如"then"而不是"The"(。 在这种情况下,更换目前正在进行,而不应该进行。

您可以按如下方式解决这两个问题:

for(int j=0 ;j<=line.length()-length_of_stopword;j++){
    if ( j+length_of_stopword<=line.length()){
        if ((j==0 || line[j-1]==' ') && (j+length_of_stopword==line.length() 
           || line[j+length_of_stopword]==' ' ) ) {
            if(line.substr(j,length_of_stopword)==word){
                line.replace(j,length_of_stopword,"*");
                no_of_occurence++;
            }
        }
    }
}

在线演示