如何用另一个字符串替换字符串的所有实例? [英] How do I replace all instances of a string with another string?
问题描述
我在另一个堆栈问题上发现了这个问题:
I found this on another stack question:
//http://stackoverflow.com/questions/3418231/c-replace-part-of-a-string-with-another-string
//
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
size_t end_pos = start_pos + from.length();
str.replace(start_pos, end_pos, to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
和我的方法:
string convert_FANN_array_to_binary(string fann_array)
{
string result = fann_array;
cout << result << "\n";
replaceAll(result, "-1 ", "0");
cout << result << "\n";
replaceAll(result, "1 ", "1");
return result;
}
其中,对于此输入:
cout << convert_FANN_array_to_binary("1 1 -1 -1 1 1 ");
现在,输出应为110011
now, the output should be "110011"
这里是方法的输出:
1 1 -1 -1 1 1 // original
1 1 0 1 // replacing -1's with 0's
11 1 // result, as it was returned from convert_FANN_array_to_binary()
我一直在看replaceAll代码,我真的不知道为什么用一个0代替连续的-1,然后不返回任何0(和一些1)最后结果。 = \
I've been looking at the replaceAll code, and, I'm really not sure why it is replacing consecutive -1's with one 0, and then not returning any 0's (and some 1's) in the final result. =\
推荐答案
错误在 str.replace(start_pos,end_pos,to) / code>
The bug is in str.replace(start_pos, end_pos, to);
从std :: string doc http://www.cplusplus.com/reference/string/string/replace/
From the std::string doc at http://www.cplusplus.com/reference/string/string/replace/
string& replace ( size_t pos1, size_t n1, const string& str );
您正在使用结束位置,而函数需要一个长度。
You are using an end-position, while the function expects a length.
因此改为:
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // ...
}
注意:未经测试。
这篇关于如何用另一个字符串替换字符串的所有实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!