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

Suppose I want to delete everything after the last '*' (for example) in a string. Knowing that for this line I can accept the following:

  • It will ALWAYS contain '*'
  • MAY contain more than one * *
  • It will NEVER start or end with the '*' symbol

What is the cleanest and / or shortest way to remove all of the past from the last '*', plus myself, only with base libraries?

+6
source share
1 answer

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); } 
+17
source

Source: https://habr.com/ru/post/978101/


All Articles