Reputation: 32635
Suppose I have the following:
std::string some_string = "2009-06-27 17:44:59.027";
The question is: Give code that will replace all instances of "-" and ":" in some_string with a space i.e. " "
I'm looking for a simple one liner (if at all possible)
Boost can be used.
Upvotes: 2
Views: 1034
Reputation: 4025
replace_if(str.begin(), str.end(), [&](char c) -> bool {
return c == '-' || c == '.';
}, ' ');
This is 1 liner using C++11. If not use functors:
replace_if(str.begin(), str.end(), CanReplace, ' ');
typedef string::iterator Iterator;
bool CanReplace(char t)
{
return t == '.' || t == '-';
}
Upvotes: 2
Reputation: 441
Boost has a string algorithm library that seems to fly under the radar:
String Algorithm Quick Reference
There is a regex based version of replace, similar to post 1, but I found find_format_all
better performance wise. It's a one-liner to boot:
find_format_all(some_string,token_finder(is_any_of("-:")),const_formatter(" "));
Upvotes: 5
Reputation: 82535
I would just write it like this:
for (string::iterator p = some_string.begin(); p != some_string.end(); ++p) {
if ((*p == '-') || (*p == ':')) {
*p = ' ';
}
}
Not a concise one-liner, but I'm pretty sure it will work right the first time, nobody will have any trouble understanding it, and the compiler will probably produce near-optimal object code.
Upvotes: 4
Reputation: 137780
replace_if( some_string.begin(), some_string.end(), boost::bind( ispunct<char>, _1, locale() ), ' ' );
One line and not n^2 running time or invoking a regex engine ;v) , although it is a little sad that you need boost for this.
Upvotes: 6
Reputation: 200766
From http://www.cppreference.com/wiki/string/find_first_of
string some_string = "2009-06-27 17:44:59.027";
size_type found = 0;
while ((found = str.find_first_of("-:", found)) != string::npos) {
some_string[found] = ' ';
}
Upvotes: 2
Reputation: 135265
You could use Boost regex to do it. Something like this:
e = boost::regex("[-:]");
some_string = regex_replace(some_string, e, " ");
Upvotes: 4