views:

316

answers:

6

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.

+2  A: 

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] = ' ';
}
John Millikin
+4  A: 

You could use Boost regex to do it. Something like this:

e = boost::regex("[-:]");
some_string = regex_replace(some_string, e, " ");
1800 INFORMATION
sweet. thank you.
ShaChris23
+4  A: 

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.

Kristopher Johnson
+6  A: 
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.

Potatoswatter
Note that this will replace all punctuation characters, not just ':' and '-'. `ispunct<char>` should be replaced with a function that does what is specified.
Kristopher Johnson
replace( some_string.begin(), some_string.end(), ':', ' ' );replace( some_string.begin(), some_string.end(), '-', ' ' );
Potatoswatter
+1 for the note about the n^2 running time and/or use of regex engines for other answers. I know that thinking about performance is out-of-fashion, but if one doesn't care about performance, why the hell would they bother with C++?
Kristopher Johnson
+2  A: 
replace_if(str.begin(), str.end(), [&](char c) -> bool{
 if (c == '-' || c == '.')
  return true;
 else 
  return false;
}, ' ');

This is 1 liner using c++ox. If not use functors.

replace_if(str.begin(), str.end(), CanReplace, ' ');

typedef string::iterator Iterator;

bool CanReplace(char t) { if (t == '.' || t == '-') return true; else return false; }

Jagannath
+2  A: 

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(" "));
Fat Elvis
ooh..this is cool too. thanks!
ShaChris23