你似乎没有初始化 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 ....
start_pos
初始化为0。 - Alan Stokes