2

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.

6 Answers 6

6
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.

Sign up to request clarification or add additional context in comments.

3 Comments

Note that this will replace all punctuation characters, not just ':' and '-'. ispunct<char> should be replaced with a function that does what is specified.
replace( some_string.begin(), some_string.end(), ':', ' ' ); replace( some_string.begin(), some_string.end(), '-', ' ' );
+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++?
5

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(" ")); 

Comments

4

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

e = boost::regex("[-:]"); some_string = regex_replace(some_string, e, " "); 

Comments

4

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.

Comments

2

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] = ' '; } 

Comments

2
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 == '-'; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.