I need to trim the beginning or end of a string, given a matching character.
My function definition looks:
void trim(std::string &s, char c, bool reverse = false);
The bool reverse
flags whether to trim the beginning (false) or end (true) of the string.
For example:
s = "--myarg--";
trim(s, '-', false); // should set s to "myarg--"
trim(s, '-', true); // should set s to "--myarg"
To trim the beginning (i.e. reverse=false
), this works fine:
bool ok = true;
auto mayberemove = [&ok](std::string::value_type ch){if (ch != '-') ok = false; return ok;};
s.erase(std::remove_if(s.begin(), s.end(), mayberemove), s.end());
The lambda just returns true
for each character matching '-', up until the first occurrence of a non-matching character, and continues to return false thereafter. Here I've hard-coded the matching char to be '-', to make the code easier to read.
The trouble I am having is with trimming in reverse. This doesn't work - same as above, but with reverse iterators and ::base():
s.erase(std::remove_if(s.rbegin(), s.rend(), mayberemove).base(), s.end());
Instead, the line above trims all of the ending characters except for the first two.
Any ideas? Thanks