sivabudh
sivabudh

Reputation: 32635

C++: Looking for a concise solution to replace a set of characters in a std::string with a specific character

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

Answers (6)

Jagannath
Jagannath

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

Fat Elvis
Fat Elvis

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

Kristopher Johnson
Kristopher Johnson

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

Potatoswatter
Potatoswatter

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

John Millikin
John Millikin

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

1800 INFORMATION
1800 INFORMATION

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

Related Questions