C++ : Error while replacing character

标签 c++ string replace

我正在尝试替换“;”在一个带有子字符串的字符串中,稍后我将在其上拆分我的流。 现在的问题是 string::replace()。这是代码:

std::string Lexer::replace(const std::string &line) const
{
  std::size_t   start_pos;
  std::string   tmp(line);

  start_pos = 0;
  while ((start_pos = tmp.find(";", start_pos)) != std::string::npos)
  {
    tmp.replace(start_pos, 1, " ");
    start_pos += 1;
  }
  return (tmp);
}

line 字符串可以是这样的:word1 word2 word3; word1 word2 word3;.... 它适用于像 word1 word2 word3; 这样的字符串,但这是我得到的像 word1 word2 word3; 这样的字符串。 word1 word2 word3; :

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::replace
Aborted

我看不出我做错了什么。我读到当 string::replace(pos, len, substr) 中的给定位置等于 string::npos 时会发生此错误,所以为什么我的条件循环无助于避免它?

谢谢。

最佳答案

您似乎没有初始化 start_pos,因此您需要更改这一行:

std::size_t   start_pos = 0;
//                     ^^^^

否则,您会得到未定义的行为,其中一些垃圾值可能代表起始位置。

另外,请注意,您最好使用 string::size_type,因为您在迭代时在这里处理字符串大小。

这段代码对我来说很好用:

main.cpp

#include <string>
#include <iostream>

using namespace std;

string myreplace(const string &line)
{
    string::size_type   start_pos = 0;
    string   tmp(line);

    while ((start_pos = tmp.find(";", start_pos)) != string::npos)
    {
        tmp.replace(start_pos, 1, " ");
        start_pos += 1;
    }
    return tmp;
}

int main()
{
    string test_str1 = "word1 word2 word3;";
    string test_str2 = "word1 word2 word3; word1 word2 word3;";
    string test_str3 = "word1 word2 word3; word1 word2 word3;....";

    cout << myreplace(test_str1) << endl;
    cout << myreplace(test_str2) << endl;
    cout << myreplace(test_str3) << endl;

    return 0;
}

输出

word1 word2 word3 
word1 word2 word3  word1 word2 word3 
word1 word2 word3  word1 word2 word3 ....

============================================= ===

话虽如此,您应该考虑使用 std 中的标准替换算法,如下所示:

#include <string>
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    string test_str1 = "word1 word2 word3;";
    string test_str2 = "word1 word2 word3; word1 word2 word3;";
    string test_str3 = "word1 word2 word3; word1 word2 word3;....";

    string out_str1 = replace(test_str1.begin(), test_str1.end(), ';', ' ');
    string out_str2 = replace(test_str2.begin(), test_str2.end(), ';', ' ');
    string out_str3 = replace(test_str3.begin(), test_str3.end(), ';', ' ');

    cout << out_str1 << endl;
    cout << out_str2 << endl;
    cout << out_str3 << endl;
    return 0;
}

输出

word1 word2 word3 
word1 word2 word3  word1 word2 word3 
word1 word2 word3  word1 word2 word3 ....

关于C++ : Error while replacing character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23311803/

相关文章:

c++ - 哪些消息可以传递给低级鼠标钩子(Hook)回调函数?

c++ - 叉积的输出

c++ - Boost 的 Sublime Text 2 问题

c# - 打乱字符串,使相邻的两个字母不相同

python - 我是否需要在字符串连接中传递多个变量

使用 replace_with_na 函数用 NA 替换范围外的值

mysql - SQL 替换功能在我的情况下不起作用

c++ - Qt Designer 和样式表

string - 这是什么编码/压缩算法?

ruby-on-rails - 在 ruby​​ 中用另一个数组中的字符串替换一个数组中的字符串