Reputation: 37
I have a task. There are 2 strings: S and s. I need to remove the last substring of S, that is the same with s. For
S = [123 234 789 123]
s = [123]
result = [123 234 789]
Upvotes: -1
Views: 88
Reputation: 537
#include <iostream>
#include <string>
int main() {
std::string S = "123xyzxyz1234";
std::string s = "123";
// The last instance of s starts from index p of S
auto p = S.rfind(s);
auto tail = S.substr(p + s.length());
if (p != std::string::npos) {
S.resize(p);
S += tail;
}
std::cout << "S = " << S << std::endl;
}
The if
statement guards against not found
cases.
Upvotes: 2
Reputation: 780
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
string removeLastSubstr(string S, string s)
{
reverse(S.begin(), S.end());
reverse(s.begin(), s.end());
if (s.find(s) != string::npos)
S = S.substr(S.find(s) + s.size(), S.size());
reverse(S.begin(), S.end());
return S;
}
Upvotes: 0
Reputation: 15824
If none of your character from second substring is not repeating again before the last part of your substring, this will work:
std::string S ="123234789123";
std::string s="123";
auto it= S.find_last_of(s[0]);
std::cout<<S.substr(0,it);
Upvotes: 0
Reputation: 4343
Since the code shown is independent of any implementation details, I will give the brief overview of how to do this.
string S,s; // I am assuming they contain the right data
int position = S.rfind(s);
string ans1 = S.substr(0, position);
string ans2 = S.substr(position + s.length());
return ans1 + ans2;
There might be off by one errors in the code above, and some safety checks may be required. But I'm leaving that to you.
Upvotes: 0