tags:

views:

237

answers:

3

What is the effective way to replace all occurrences of a character with another character in std::string?

+13  A: 

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

std::string s = SOME_STR;
std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
Kirill V. Lyadvinsky
Thnx, didn't know that std::string is a container.
big-z
`std::string` is **a container** specifically designed to operate with sequences of characters. [link](http://www.cplusplus.com/reference/string/string/)
Kirill V. Lyadvinsky
A: 

As Kirill suggested, either use the replace method or iterate along the string replacing each char independently.

Alternatively you can use the find method or find_first_of depending on what you need to do. None of these solutions will do the job in one go, but with a few extra lines of code you ought to make them work for you. :-)

Konrad
A: 

A simple find and replace for a single character would go something like:

s.replace(s.find("x"), 1, "y")

To do this for the whole string, the easy thing to do would be to loop until your s.find starts returning npos. I suppose you could also catch range_error to exit the loop, but that's kinda ugly.

T.E.D.
While this is probably a suitable solution when the number of characters to replace is small compared to the length of the string, it doesn't scale well. As the proportion of characters in the original string that need to be replaced increases, this method will approach O(N^2) in time.
andand
True. My general philosophy is to do the easy (to write and to read) thing until such time as the inefficiencies are causing real problems. There are some circumstances where you might have humoungous strings where O(N**2) matters, but 99% of the time my strings are 1K or less.
T.E.D.
...that being said, I like Kirill's method better (and had already voted it up).
T.E.D.