2

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?

1
  • "Is there a library (e.g. boost) supporting replacement with wildcards or something similar?" Regular expressions? Commented Nov 9, 2017 at 16:01

2 Answers 2

2

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

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

Provided substring is found in string

Sign up to request clarification or add additional context in comments.

Comments

0
#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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.