获取 C 中字符串的最后一个标记 [英] get the last token of a string in C

查看:53
本文介绍了获取 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.

例如:

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;

我希望我的回归是

字符串

但我得到的是(空).任何解决方法?我在网上搜索过,似乎无法找到答案.至少对于 C 编程语言来说是这样.

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.

推荐答案

如果您对特定字符进行标记,即在您的示例中是 '/',则根本不需要对字符串进行标记: 调用strrchr 找到最后一个的位置'/',并将 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);
}

演示.

这篇关于获取 C 中字符串的最后一个标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆