【问题标题】:std::out_of_range when using string find and replace inside while loop在while循环中使用字符串查找和替换时的std :: out_of_range
【发布时间】:2017-05-13 22:45:05
【问题描述】:

所以我的任务是将一个字符串中某个单词的所有出现转换为另一个字符串。但是while循环的条件有问题导致这个错误

在抛出 'std::out_of_range' 的实例后调用终止

what(): basic_string::replace

此应用程序已请求运行时以不寻常的方式终止它。请联系应用程序的支持团队以获取更多信息。进程返回 3 (0x3) 执行时间:2.751 s

我的代码是:

#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string str2("three");
    string str("one three two four three three");
    while ( str.find(str2) != NULL ){
    str.replace(str.find(str2),str2.length(),"five");
    cout << str << endl; // i put it inside loop to see output
    }
    cout << str << endl;
    return 0;
}

有什么建议吗?

【问题讨论】:

    标签: c++ string replace while-loop find


    【解决方案1】:

    您正在检查 str.find(str2) 是否发生了将其与 NULL 进行比较的情况,但这是错误的,因为 NULL 是一个不适用于此的宏,并且经常扩展为 0可以是一个有效的索引。您应该将其与std::string::npos 进行比较。进行此更改后,您的代码将正常工作。

    编辑:std::string::npos 对应于在 coliru 上测试时的18446744073709551615。所以这显然不是你的字符串中的有效索引。

    【讨论】:

    • 感谢您的帮助。
    【解决方案2】:

    这个条件

    while ( str.find(str2) != NULL ){
    

    没有意义,因为调用find 可以返回不等于零的std::string::npos。在这种情况下,代码具有未定义的行为。

    您可以应用以下方法

    std::string str2("three");
    std::string str("one three two four three three");
    
    const char *five = "five";
    size_t n = std::strlen(five);
    
    for (std::string::size_type pos = 0;
        ( pos = str.find(str2, pos) ) != std::string::npos; pos += n)
    {
        str.replace(pos, str2.length(), five);
    }
    

    【讨论】:

      【解决方案3】:

      这是因为如果str 中不存在str2,则str.find(str2) 返回-1。您可以使用变量pos 来保存找到的位置,这样您就不需要重新调用find 函数。解决方案如下:

      #include <iostream>
      #include <string>
      using namespace std;
      int main () {
        string str2("three");
        string str("one three two four three three");
        int pos = str.find(str2);
        while (pos > 0) {
          str.replace(pos, str2.length(), "five");
          pos = str.find(str2);
          cout << str << endl; // i put it inside loop to see output
        }
        cout << str << endl;
        return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-26
        • 2021-03-14
        • 1970-01-01
        • 1970-01-01
        • 2017-09-30
        • 2021-12-19
        • 1970-01-01
        相关资源
        最近更新 更多