我正在尝试替换“;”在一个带有子字符串的字符串中,稍后我将在其上拆分我的流。
现在的问题是 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/