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 (ie 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
std::string& trim( std::string& s, char c, bool reverse = false )
{
return reverse
? s.erase( s.find_last_not_of( c ) + 1 )
: s.erase( 0, s.find_first_not_of( c ) );
}
Well, actually I just figured it out. It looks like I needed to reverse the logic of the mayberemove
lambda for the reverse case. So, this appears to work fine:
if (reverse) {
bool notok = false;
auto mayberemove = [¬ok](std::string::value_type ch){if (ch != '-') notok = true; return notok;};
s.erase(std::remove_if(s.rbegin(), s.rend(), mayberemove).base(), s.end());
}
else {
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());
}
And that works. Now I just need to understand why.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.