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?
To get the last word of a string:Call the split() method on the string, passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Call the pop() method to get the value of the last element (word) in the array.
Because C uses null-terminated strings, which means that the end of any string is marked by the ASCII value 0 (the null character), which is also represented in C as '\0'.
Approach: Append a space i.e. ” “ at the end of the given string so that the last word in the string is also followed by a space just like all the other words in the string. Now start traversing the string character by character, and print every character which is followed by a space.
The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string . If the given character is not found, a NULL pointer is returned.
Something like this:
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With