traversing C string: get the last word of a string

10,064

Solution 1

Something like this:

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

Solution 2

In case you don't want to use 'strrchr' function, Here is the solution.

i = 0;
char *last_word;

while (str[i] != '\0')
{
    if (str[i] <= 32 && str[i + 1] > 32)
        last_word = &str[i + 1];
    i++;
}
i = 0;
while (last_word && last_word[i] > 32)
{
    write(1, &last_word[i], 1);
    i++;
}
Share:
10,064
user1000219
Author by

user1000219

Updated on June 20, 2022

Comments

  • user1000219
    user1000219 almost 2 years

    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?