【发布时间】:2011-03-17 17:58:56
【问题描述】:
我在另一个堆栈问题上找到了这个:
//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”
这里是方法的输出:
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)。 =\
【问题讨论】:
-
在这个特定的例子中,似乎另一种解决方案更合适——即根本不使用字符串操作,使用整数/布尔数组。
-
它必须是字符串,因为我们是从一个 ascii 文件中读取的。
-
如果您遵循@Konrad 的建议,您可以使用std::replace 替换值。您从 ascii 文件中读取的事实没有理由不将您的数字表示为整数。
-
然后转换它们。程序的流程总是一样的:1.读取输入,2.转换为适当的格式,3.应用计算,4.转换为输出格式,5.输出。你正试图跳过第 (2) 步,让你的生活变得不必要地艰难。字符串很少适合文本以外的任何内容。
-
同意。我们需要在我们的库中重新编写一个方法,然后才能读取序列化文件。我们会到达那里。