How to remove the last n occurrences of a substring in a string in C++

2 Answers

0 votes
#include <iostream>
#include <string>
#include <vector>
  
std::string remove_last_n_occurrences(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 to avoid shifting earlier positions
    for (int i = positions.size() - 1; i >= 0 && n > 0; --i, --n) {
        s.erase(positions[i], sub.length());
    }
  
    return s;
}
  
int main() {
    std::string text = "abc xyz xyz abc xyzabcxyz abc";
    std::cout << remove_last_n_occurrences(text, "xyz", 3) << "\n";
}
  
  
  
/*
run:
  
abc xyz  abc abc abc
  
*/

 



answered Feb 15 by avibootz
edited Feb 16 by avibootz
0 votes
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
 
// Remove last n occurrences of substring
std::string remove_last_n_occurrences(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_occurrences(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
 
*/

 



answered Feb 15 by avibootz
edited Feb 16 by avibootz

Related questions

...