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

2 Answers

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

using std::cout;
using std::endl;
using std::string;

string LastWord(string s)
{
	string::size_type pos = s.find_last_of(" ");

	if (string::npos != pos)
		s = s.substr(pos + 1);

	return s;
}

int main()
{
	string s = "c++ c c# java php";

	cout << LastWord(s) << endl;

	return 0;
}


/*
run:

php

*/

 



answered Apr 18, 2018 by avibootz
edited Apr 19, 2018 by avibootz
0 votes
#include <iostream>
#include <string>
#include <cctype>

// Returns the last word from a string.
// Empty or whitespace-only strings return an empty string.
std::string getLastWord(const std::string& input) {
    // Trim leading/trailing whitespace
    size_t start = input.find_first_not_of(" \t\n\r");
    size_t end   = input.find_last_not_of(" \t\n\r");

    // If empty after trimming, return empty string
    if (start == std::string::npos || end == std::string::npos) {
        return "";
    }

    std::string trimmed = input.substr(start, end - start + 1);

    // Find last space
    size_t pos = trimmed.find_last_of(' ');

    // If no space found, the whole trimmed string is the last word
    if (pos == std::string::npos) {
        return trimmed;
    }

    // Return substring after the last space
    return trimmed.substr(pos + 1);
}

int main() {
    std::string tests[] = {
        "rust javascript php c c++ c# python swift",
        "",
        "c#",
        "c c++ java ",
        "  "
    };

    for (int i = 0; i < 5; i++) {
        std::cout << (i + 1) << ". " << getLastWord(tests[i]) << "\n";
    }
}


/*
run:

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

*/

 



answered Mar 27 by avibootz
...