Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ character replace

What is the best way to replace characters in a string?

Specifically:

"This,Is A|Test" ----> "This_Is_A_Test"

I want to replace all commas, spaces, and "|" with underscores.

(I have access to Boost.)

like image 427
tinkertime Avatar asked Nov 30 '09 15:11

tinkertime


1 Answers

You could use the standard replace_if algorithm, except the predicate is rather complicated (to be expressed inline with current C++ standard and no lambda).

You could write your own, or use is_any_of from boost's string algorithms, so:

#include <algorithm>
#include <string>
#include <boost/algorithm/string/classification.hpp>
#include <iostream>

int main()
{
    std::string s("This,Is A|Test");
    std::replace_if(s.begin(), s.end(), boost::is_any_of(", |"), '_');
    std::cout << s << '\n';
}
like image 125
UncleBens Avatar answered Oct 04 '22 18:10

UncleBens