traversing C string: get the last word of a string

user1000219 picture user1000219 · Feb 9, 2012 · Viewed 8.7k times · Source

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?

Answer

cnicutar picture cnicutar · Feb 9, 2012

Something like this:

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