Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

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?

like image 701
leinaD_natipaC Avatar asked Nov 12 '14 17:11

leinaD_natipaC


1 Answers

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);
}
like image 110
Mike Seymour Avatar answered Sep 21 '22 21:09

Mike Seymour