get the last token of a string in C

不羁的心 提交于 2019-12-10 23:45:34

问题


what I want to do is given an input string, which I will not know it's size or the number of tokens, be able to print it's last token.

e.x.:

char* s = "some/very/big/string";
char* token;

const char delimiter[2] = "/";

token = strtok(s, delimiter);

while (token != NULL) {
    printf("%s\n", token);
    token = strtok(NULL, delimiter);
}

return token;

and i want my return to be

string

but I what I get is (null). Any workarounds? I've searched the web and can't seem to find an answer to this. At least for C programming language.


回答1:


If you tokenize on a specific character, i.e. '/' in your example, you do not need to tokenize the string at all: call strrchr to find the position of the last '/', and add 1 to the resultant pointer to skip the delimiter, like this:

char *s = "some/very/big/string";
char *last = strrchr(s, '/');
if (last != NULL) {
    printf("Last token: '%s'\n", last+1);
}

Demo.




回答2:


Just use another variable to store last token before it gets null

char s[] = "some/very/big/string";
char * token, * last;
last = token = strtok(s, "/");
for (;(token = strtok(NULL, "/")) != NULL; last = token);
printf("%s\n", last);


来源:https://stackoverflow.com/questions/32822988/get-the-last-token-of-a-string-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!