为什么程序显示字符串超出范围
Why the program show that the string is out of range?
我正在做关于从字符串中删除一些单词的功课。它总是显示字符串超出范围,我不知道我的代码出了什么问题。
有我用来测试我的函数的字符串:
- "房子转了两三圈,慢慢升起">
- "通过空气。多萝西觉得自己好像在气球上飞起来。
- "南北风在房子所在的地方相遇,并使其成为">
- "正是旋风的中心。">
以下是我必须从上述字符串中删除的单词:
- 一个
- 一
- 一个
- 和
- 这
- 这
- 在
- 或
- 之
该程序在前两行运行良好,但它表明它超出了第三行的范围,我认为这是因为我必须从第三行中删除最后一个单词(即"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++;
}
}
}
}
在线演示
相关文章:
- C++ - 使用基于范围的 for 循环将字符值分配给向量中的字符串不会分配值
- 字符串的矢量并使用 C++20 范围进行转换
- C++ - 成功打印超出范围的字符串索引
- C++十进制到十六进制(字符串下标超出范围)
- 如何修复范围内的字符串声明错误
- C++ 字符串订阅超出范围的问题
- 在遍历字符串时,为什么我没有超出范围错误,即使我已经超出了它的长度?
- 初始检查以查看子字符串是否在范围内
- 在此范围C 中未声明字符串和char变量
- 尝试对字符串[数组]>>cin 并出现错误(" "字符串下标超出范围")
- 如何在 C++ 的字符串中打印从一个索引到另一个索引的字符范围
- C++:,当我使用字符串数组时,它的字符串下标超出了范围
- 如何将标准::字符串拆分为标准::string_views的范围 (v3)
- 为带有带前缀的字符串的容器查找相等的范围
- 为什么程序显示字符串超出范围
- 字符串订阅超出范围 - 字符串气泡排序
- 使用std :: quare_range查找字符串向量中发生的前缀范围
- 范围基于循环,使用指示字符串的指针
- 为什么在范围中未声明此字符串
- 用于匹配 C++ 范围字符串文本的正则表达式 (L "..." )