C++:如何用另一个字符替换字符串中一个字符的所有实例?

标签 c++

我在网上找到了这个方法:

//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;
}

会将 as 变成 b 并将 ds 变成 cs(虽然为什么你会对仅包含 0 和 1 的字符串执行此操作,我无法想象)。但是,它不会插入任何额外的空格。

如果您确实需要额外的空格,请参阅 (1) Timo Geusch 提供的引用和 (2) 此:Replace part of a string with another string .

关于C++:如何用另一个字符替换字符串中一个字符的所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5342045/

相关文章:

c++ - 如何比较 vector ?

c++ - 为什么迭代 `std::vector` 比迭代 `std::array` 更快?

c++ - 表达式中运算符的 GCC 和 ADL

c++ - 来自 boost::operators 的意外行为

c++ - 如何使用 C 或 C++ 在 Linux 上获取已安装的 True Type 字体列表?

c++ - 应用程序的 .exe 文件缺少 .NET TargetFramework,但仅在干净的构建中

c++ - 从 C++ 文件写入数据(点云库)

c++ - 如何在另一个 C++ 程序中运行一个 C++ 程序?

c++ - QNetworkReply 和 301 重定向

c++ - 我可以将 CFPropertyList WriteToStream 与 stderr 一起使用吗?