Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

traversing C string: get the last word of a string

Tags:

c

string

strncpy

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?

like image 252
user1000219 Avatar asked Feb 09 '12 22:02

user1000219


People also ask

How do I get the last word in a string?

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.

How does C know the end of a string?

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'.

How do I print the last element of a string?

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.

How do you check if the character is the end of a string in C?

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.


1 Answers

Something like this:

char *p = strrchr(str, ' ');
if (p && *(p + 1))
    printf("%s\n", p + 1);
like image 122
cnicutar Avatar answered Oct 18 '22 00:10

cnicutar