leinaD_natipaC
leinaD_natipaC

Reputation: 4437

Elegantly removing the part of a string after the last occurrence of a character

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:

  1. It will ALWAYS contain a '*'
  2. It MAY contain more than one '*'
  3. It will NEVER start or end with a '*'

What is the cleanest and/or shortest way to remove everything past the last '*', plus itself, with only basic libraries?

Upvotes: 11

Views: 7013

Answers (2)

wu1meng2
wu1meng2

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

Mike Seymour
Mike Seymour

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

Related Questions