#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Returns the last word from a string.
// Empty or whitespace-only strings return an empty string.
void getLastWord(const char *input, char *output) {
const char *start = input;
const char *end = input + strlen(input);
// Trim trailing whitespace
while (end > start && isspace((unsigned char)*(end - 1))) {
end--;
}
// Trim leading whitespace
while (start < end && isspace((unsigned char)*start)) {
start++;
}
// If empty after trimming, return empty string
if (start == end) {
output[0] = '\0';
return;
}
// Find the last space before the end
const char *lastSpace = NULL;
for (const char *p = start; p < end; p++) {
if (isspace((unsigned char)*p)) {
lastSpace = p;
}
}
// If no space found, the whole trimmed string is the last word
if (!lastSpace) {
size_t len = end - start;
memcpy(output, start, len);
output[len] = '\0';
return;
}
// Otherwise copy the substring after the last space
const char *wordStart = lastSpace + 1;
size_t len = end - wordStart;
memcpy(output, wordStart, len);
output[len] = '\0';
}
int main(void) {
const char *tests[] = {
"vb.net javascript php c c# c++ python kotlin",
"",
"c#",
"c c++ java ",
" "
};
char result[128];
for (int i = 0; i < 5; i++) {
getLastWord(tests[i], result);
printf("%d. %s\n", i + 1, result);
}
return 0;
}
/*
run:
1. kotlin
2.
3. c#
4. java
5.
*/