#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.
*/