Reputation: 4437
Suppose I want to remove everything after the last '*' (for example) in a string. Knowing that I can take the following for granted for that string:
What is the cleanest and/or shortest way to remove everything past the last '*', plus itself, with only basic libraries?
Upvotes: 11
Views: 7013
Reputation: 537
Since rfind
returns the index of the target char or string, we can also use resize
to cut the unwanted part of the input string.
s.resize(s.rfind('*'));
Upvotes: 2
Reputation: 254431
Given your assumptions:
s.erase(s.rfind('*'));
Without the assumption that it contains at least one *
:
auto pos = s.rfind('*');
if (pos != std::string::npos) {
s.erase(pos);
}
Upvotes: 25