【问题标题】:Why the program show that the string is out of range? [closed]为什么程序显示字符串超出范围? [关闭]
【发布时间】:2019-03-31 01:07:08
【问题描述】:

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

我使用了一些字符串来测试我的功能:

  • “房子转了两三圈,缓缓升起”
  • “在空中。Dorothy 感觉自己就像在气球里一样。”
  • “南北风在房子所在的地方相遇,并使其成为”
  • “旋风的确切中心。”

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

  • 一个
  • 一个
  • 一个

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

  }
}

【问题讨论】:

  • 你有没有用铅笔和一些纸来检查你的数学问题?您是否使用调试器逐步完成了该程序?你发现了什么?
  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建minimal reproducible example
  • 建议 -- line.substr(j-1,1)==" " -- 这是检查单个字符是否为空格的最糟糕的方法之一。这可能只是line[j-1] == ' '
  • 我用铅笔解决了这个问题,但我找不到字符串超出范围的原因。
  • 字符串没有超出范围。这是没有意义的。字符串 index 超出范围。准确。

标签: c++ string c++11


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    作为answer from David explained,您需要动态检查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++;
                }
            }
        }
    }
    

    Online demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-20
      • 2022-07-05
      • 1970-01-01
      • 2011-12-05
      • 2017-03-16
      • 1970-01-01
      • 2015-04-27
      相关资源
      最近更新 更多