#include <iostream>
#include <string>
#include <vector>
#include <sstream>
// Remove last n occurrences of substring
std::string remove_last_n(std::string s, const std::string& sub, int n) {
std::vector<size_t> positions;
size_t pos = s.find(sub);
while (pos != std::string::npos) {
positions.push_back(pos);
pos = s.find(sub, pos + sub.length());
}
// Remove from the end
for (int i = positions.size() - 1; i >= 0 && n > 0; --i, --n) {
s.erase(positions[i], sub.length());
}
return s;
}
// Remove extra spaces and trim
std::string remove_extra_spaces(const std::string& s) {
std::stringstream ss(s);
std::string word, result;
while (ss >> word) {
if (!result.empty())
result += " ";
result += word;
}
return result;
}
int main() {
std::string text = "abc xyz xyz abc xyzabcxyz abc";
std::string result = remove_last_n(text, "xyz", 3);
std::cout << result << "\n";
std::string cleaned = remove_extra_spaces(result);
std::cout << cleaned << "\n";
}
/*
run:
abc xyz abc abc abc
abc xyz abc abc abc
*/