C - 确定使用哪个分隔符 - strtok() [英] C - Determining which delimiter used - strtok()

查看:53
本文介绍了C - 确定使用哪个分隔符 - strtok()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我像这样使用 strtok()..

Let's say I'm using strtok() like this..

char *token = strtok(input, ";-/");

有没有办法确定实际使用了哪个令牌?例如,如果输入类似于:

Is there a way to figure out which token actually gets used? For instance, if the inputs was something like:

Hello there; How are you? / I'm good - End

我能找出每个令牌使用了哪个分隔符吗?我需要能够输出特定的消息,具体取决于令牌后面的分隔符.

Can I figure out which delimiter was used for each token? I need to be able to output a specific message, depending on the delimiter that followed the token.

推荐答案

重要提示:strtok 不可重入,您应该使用 strtok_r 而不是它.

Important: strtok is not re-entrant, you should use strtok_r instead of it.

您可以通过保存原始字符串的副本,然后查看当前标记在该副本中的偏移量来实现:

You can do it by saving a copy of the original string, and looking into offsets of the current token into that copy:

char str[] = "Hello there; How are you? / I'm good - End";
char *copy = strdup(str);
char *delim = ";-/";
char *res = strtok( str, delim );
while (res) {
    printf("%c\n", copy[res-str+strlen(res)]);
    res = strtok( NULL, delim );
}
free(copy);

打印出来

;
/
-

演示 #1

处理多个分隔符

如果需要处理多个定界符,确定当前定界符序列的长度会稍微困难一些:现在您需要先找到下一个标记,然后再决定定界符序列有多长.数学并不复杂,只要你记住 NULL 需要特殊处理:

If you need to handle multiple delimiters, determining the length of the current sequence of delimiters becomes slightly harder: now you need to find the next token before deciding how long is the sequence of delimiters. The math is not complicated, as long as you remember that NULL requires special treatment:

char str[] = "(20*(5+(7*2)))+((2+8)*(3+6*9))";
char *copy = strdup(str);
char *delim = "*+()";
char *res = strtok( str, delim );
while (res) {
    int from = res-str+strlen(res);
    res = strtok( NULL, delim );
    int to = res != NULL ? res-str : strlen(copy);
    printf("%.*s\n", to-from, copy+from);
}
free(copy);

演示 #2

这篇关于C - 确定使用哪个分隔符 - strtok()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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