What is the effective way to replace all occurrences of a character with another character in std::string
?
views:
237answers:
3
+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
2010-05-24 11:33:32
Thnx, didn't know that std::string is a container.
big-z
2010-05-24 11:39:40
`std::string` is **a container** specifically designed to operate with sequences of characters. [link](http://www.cplusplus.com/reference/string/string/)
Kirill V. Lyadvinsky
2010-05-24 11:41:52
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
2010-05-24 11:36:44
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.
2010-05-24 11:56:37
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
2010-05-24 14:37:26
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.
2010-05-25 03:40:17
...that being said, I like Kirill's method better (and had already voted it up).
T.E.D.
2010-05-25 03:41:16