C ++: How to replace all instances of a character in a string with another character?

I found this method on the Internet:

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

But it gives

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])’
+3
source share
3 answers

You need characters, not strings, as the third and fourth arguments for replace. Of course, this will not happen if you really want to replace 'a'with "b ".

For example,

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

will turn ainto band dinto c(although why are you doing this with a string containing only 0 and 1, I can’t imagine). However, it will not insert extra spaces.

If you need extra spaces, see (1) the link provided by Timo Geusch and (2): Replace part of a string with another string .

+5

Another approach, if you want to localize a replacement, is to use a functor ...

Example:

#include <string>
#include <algorithm>

struct replaceChar
{
   void operator()(char& c) { if(c == 'a') c = 'b'; }
};

std::string str = "Ababba";

std::for_each(str.begin(), str.end(), replaceChar() );
0
source

All Articles