我在网上找到了这个方法:
//the call to the method:
cout << convert_binary_to_FANN_array("1001");
//the method in question:
string convert_binary_to_FANN_array(string binary_string)
{
string result = binary_string;
replace(result.begin(), result.end(), "a", "b ");
replace(result.begin(), result.end(), "d", "c ");
return result;
}
但这给出了
main.cpp:30: error: no matching function for call to ‘replace(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, const char [2], const char [3])’
最佳答案
您需要字符而不是字符串作为replace
的第三个和第四个参数。当然,如果您真的想将 'a'
替换为 "b "
,那是行不通的。
所以,例如,
string convert_binary_to_FANN_array(string binary_string)
{
string result = binary_string;
replace(result.begin(), result.end(), 'a', 'b');
replace(result.begin(), result.end(), 'd', 'c');
return result;
}
会将 a
s 变成 b
并将 d
s 变成 c
s(虽然为什么你会对仅包含 0 和 1 的字符串执行此操作,我无法想象)。但是,它不会插入任何额外的空格。
如果您确实需要额外的空格,请参阅 (1) Timo Geusch 提供的引用和 (2) 此:Replace part of a string with another string .
关于C++:如何用另一个字符替换字符串中一个字符的所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5342045/