HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Stripping specified character

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
strippingcharacterspecified

Problem

Here's some code that removes the specified character, ch, from the string passed in. Is there a better way to do this? Specifically, one that's more efficient and/or portable?

//returns string without any 'ch' characters in it, if any.
#include 
using namespace std;
string strip(string str, const char ch)
{
        size_t p = 0; //position of any 'ch'

        while ((p = str.find(ch, p)) != string::npos)
                str.erase(p, 1);

        return str;
}

Solution

I'm not entirely sure how the performance will compare, but the standard way to accomplish this would be the erase-remove idiom:

str.erase(std::remove(str.begin(). str.end(), ch), str.end());


Unless the performance proves to be a bottleneck, it's typically better to stick with the C++ style of doing things. I can't imagine that this would be significantly less efficient than the other method. (In fact, I wouldn't be surprised if this is a bit faster for long strings with a high amount of the removed character -- though my assumption of that depends on quite a few non-guaranteed implementation choices, and a rather rough estimation of the cost of different low level operations.)

Code Snippets

str.erase(std::remove(str.begin(). str.end(), ch), str.end());

Context

StackExchange Code Review Q#18415, answer score: 5

Revisions (0)

No revisions yet.