Search code examples
cstringstrncpy

traversing C string: get the last word of a string


how would you get the last word of a string, starting from the '\0' newline character to the rightmost space? For example, I could have something like this where str could be assigned a string:

char str[80];
str = "my cat is yellow";

How would I get yellow?


Solution

  • Something like this:

    char *p = strrchr(str, ' ');
    if (p && *(p + 1))
        printf("%s\n", p + 1);