Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string replace doesn't work as expected

small question about C++ replace function. I'm parsing every line of text input line by line. Example of the text file:

SF27_34KJ
EEE_30888
KPD324222
4230_333

And I need to remove all the underscores on every line and replace it with a comma. When I try something like this:

mystring.replace(mystring.begin(), mystring.end(), '_', ',');

on every line - instead of "SF27,34KJ" I get 95x "," char. What could be wrong?

like image 829
user1175307 Avatar asked Oct 24 '25 02:10

user1175307


2 Answers

Use std::replace():

std::replace(mystring.begin(), mystring.end(), '_', ',');
like image 82
hmjd Avatar answered Oct 26 '25 17:10

hmjd


basic_string::replace doesn't do what you think it does.

basic_string::replace(it_a, it_e, ... ) replaces all of the characters between it_a and it_e with whatever you specify, not just those that match something.

There are a hundred ways to do what you're trying to do, but the simplest is probably to use the std::replace from <algorithm>, which does do what you want:

std::replace(mystring.begin(), mystring.end(), '_', ',');

Another method is to use std::transform in conjunction with a functor. This has an advantage over std::replace in that you can perform multiple substitutions in a single pass.

Here is a C++03 functor that would do it:

struct ReplChars
{
    char operator()(char c) const
    {
        if( c == '_' )
            return ',';
        if( c == '*' )
            return '.';
        return c;
    }
};

...and the use of it:

std::transform(mystring.begin(), mystring.end(), mystring.begin(), ReplChars());

In C++11, this can be reduced by using a lambda instead of the functor:

std::transform(mystring.begin(), mystring.end(), mystring.begin(), [](char c)->char
{
    if( c == '_' )
        return ',';
    if( c == '*' )
        return '.';
    return c;
});
like image 37
John Dibling Avatar answered Oct 26 '25 18:10

John Dibling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!