Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

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(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(text, "xyz", 3) << "\n";
}
 
 
 
/*
run:
 
abc xyz  abc abc abc
 
*/

 



answered 9 hours ago by avibootz
edited 6 hours ago by avibootz
0 votes
#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
 
*/

 



answered 9 hours ago by avibootz
edited 6 hours ago by avibootz
...