How to get the last word from string in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
  
int main()
{
    char str[64] = "c c++ c# java php";
    char *p = str, *last_word;
    
    while ( (p = strchr(p,' ')) ) last_word = p++;
        
    puts(++last_word);
 
    return 0;
}
 
/*
run:
 
php
 
*/

 



answered Apr 15, 2018 by avibootz
0 votes
#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.

*/

 



answered Mar 27 by avibootz
...