a1an
a1an

Reputation: 3636

c++ Remove substring after last match of substring

What is a compact way of removing the last part of a string after the last occurrence of a given substring, including it? In terms of bash parameter substitution it would be the equivalent of:

VAR=${VAR%substring*}

Is there a library (e.g. boost) supporting replacement with wildcards or something similar?

Upvotes: 2

Views: 79

Answers (2)

wu1meng2
wu1meng2

Reputation: 537

#include <iostream>
#include <string>

int main() {
  std::string st = "abcedfgsubstring1234";
  auto pos = st.rfind("substring");
  if (pos != std::string::npos) {
    st.resize(pos);
  }
  std::cout << st << std::endl;
}

If substring is not found, do nothing.

Upvotes: 0

a1an
a1an

Reputation: 3636

Without wildcards, the solution I've found is as follows

string.erase(string.rfind("substring"));

Provided substring is found in string

Upvotes: 2

Related Questions