Reputation: 3636
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
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
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