And*_*kes 10 c tokenize strtok
假设我正在使用strtok()这样的..
char *token = strtok(input, ";-/");
Run Code Online (Sandbox Code Playgroud)
有没有办法找出实际使用哪个令牌?例如,如果输入类似于:
Hello there; How are you? / I'm good - End
我可以找出每个令牌使用哪个分隔符?我需要能够输出特定的消息,具体取决于令牌后面的分隔符.
重要提示:strtok不是可重入的,您应该使用strtok_r它而不是它.
您可以通过保存原始字符串的副本,并查看当前令牌到该副本的偏移量来实现:
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);
Run Code Online (Sandbox Code Playgroud)
这打印
;
/
-
Run Code Online (Sandbox Code Playgroud)
编辑: 处理多个分隔符
如果需要处理多个分隔符,确定当前分隔符序列的长度会变得稍微困难:现在需要在确定分隔符序列的长度之前找到下一个标记.数学并不复杂,只要你记得NULL需要特殊处理:
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);
Run Code Online (Sandbox Code Playgroud)