[英]get the last token of a string in C
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. 我想要做的是给出一个输入字符串,我不知道它的大小或标记的数量,能够打印它的最后一个标记。
ex: 例如:
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). 但我得到的是(null)。 Any workarounds?
任何解决方法? I've searched the web and can't seem to find an answer to this.
我在网上搜索过,似乎无法找到答案。 At least for C programming language.
至少对于C编程语言。
If you tokenize on a specific character, ie '/'
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: 如果您对特定字符进行标记,即在示例中为
'/'
,则根本不需要对字符串进行标记:调用strrchr
以查找最后一个'/'
的位置,并将1
添加到结果指针以跳过分隔符,像这样:
char *s = "some/very/big/string";
char *last = strrchr(s, '/');
if (last != NULL) {
printf("Last token: '%s'\n", last+1);
}
Just use another variable to store last token before it gets null 只需使用另一个变量来存储最后一个令牌,然后再获取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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.