How to remove the last occurrence of a word from a string in C++

1 Answer

0 votes
#include <iostream>
#include <string>

std::string removeLastOccurrenceOfAWordFromAString(std::string str, const std::string& word) {
    // Find the position of the last occurrence of word in str
    size_t pos = str.rfind(word);
    
    if (pos != std::string::npos) {
        str.erase(pos, word.length());
    }
    
    return str;
}
 
int main()
{
    std::string str = "c++ c python c++ java c++ php";
    std::string word = "c++";

    str = removeLastOccurrenceOfAWordFromAString(str, word);
 
    std::cout << str; 
}



/*
run:

c++ c python c++ java  php

*/

 



answered Sep 8, 2024 by avibootz
edited Sep 8, 2024 by avibootz
...