#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Remove trailing spaces
static void rtrim(char *s) {
int len = strlen(s);
while (len > 0 && isspace((unsigned char)s[len - 1])) {
s[--len] = '\0';
}
}
// Remove the last word from a space-separated string
void removeLastWord(char *s) {
rtrim(s); // First remove trailing spaces
int len = strlen(s);
if (len == 0)
return;
// Scan backward to find the last space
int i = len - 1;
while (i >= 0 && !isspace((unsigned char)s[i])) {
i--;
}
// If a space was found, truncate there
if (i >= 0)
s[i] = '\0';
}
int main(void)
{
char s[32] = "c c++ c# java python";
removeLastWord(s);
printf("1. %s\n", s);
strcpy(s, "");
removeLastWord(s);
printf("2. %s\n", s);
strcpy(s, "c");
removeLastWord(s);
printf("3. %s\n", s);
strcpy(s, "c# java python ");
removeLastWord(s);
printf("4. %s\n", s);
strcpy(s, " ");
removeLastWord(s);
printf("5. %s\n", s);
return 0;
}