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

3 Answers

0 votes
#include <iostream>
#include <string>
 
int main()
{
    std::string s = "c++ c c# java python";
  
    const auto pos = s.find_last_of(" \t\n"); 
  
    s = s.substr(0, pos);
  
    std::cout << s;
}
 
  
/*
run:
  
c++ c c# java
  
*/

 



answered Feb 25, 2017 by avibootz
edited Sep 6, 2024 by avibootz
0 votes
#include <iostream>
#include <string>
 
using std::cout;
using std::endl;
using std::string;
 
string remove_last_word(string &s) {
 
    string::size_type pos = s.rfind(' '); 
 
    if (string::npos != pos)
        s = s.substr(0, pos);
 
    return s;
}
 
 
int main()
{
    string s = "c++ c c# java php";
 
    cout << remove_last_word(s) << endl;
}
 


/*
run:
 
c++ c c# java
 
*/

 



answered Sep 6, 2024 by avibootz
0 votes
#include <iostream>
#include <string>
#include <cctype>

// Trim trailing whitespace
void rtrim(std::string &s) {
    while (!s.empty() && std::isspace(static_cast<unsigned char>(s.back()))) {
        s.pop_back();
    }
}

// Remove the last word from a space-separated string
void removeLastWord(std::string &s) {
    rtrim(s);  // Remove trailing spaces first

    if (s.empty())
        return;

    std::string::size_type pos = s.rfind(' '); 
  
    if (std::string::npos != pos)
        s.erase(pos);
}

int main() {
    std::string s;

    s = "c c++ c# java python";
    removeLastWord(s);
    std::cout << "1. " << s << "\n";

    s = "";
    removeLastWord(s);
    std::cout << "2. " << s << "\n";

    s = "c";
    removeLastWord(s);
    std::cout << "3. " << s << "\n";

    s = "c# java python ";
    removeLastWord(s);
    std::cout << "4. " << s << "\n";

    s = "  ";
    removeLastWord(s);
    std::cout << "5. " << s << "\n";
}



/*
run:

1. c c++ c# java
2. 
3. c
4. c# java
5.

*/

 



answered Mar 27 by avibootz
...