C语言中的 strtok 函数

在看一个项目的代码时,发现了它用到了strtok 这个API, 它的作用是 split 一个字符串。这个功能在各个语言都很常见,而且接口也大同小异,比如 Golang: s := strings.Split("a,b,c", ",") fmt.Println(s) // Output: [a b c] Python: txt = "hello, my name is Peter, I am 26 years old" x = txt.split(", ") print(x) 而 strtok 的接口就比较奇怪了,看一个例子: Live Demo #include <string.h> #include <stdio.h> int main () { char str[80] = "This is - www.tutorialspoint.com - website"; const char s[2] = "-"; char *token; /* get the first token */ token = strtok(str, s); /* walk through other tokens */ while( token != NULL ) { printf( " %s\n", token ); token = strtok(NULL, s); } return(0); } 输出为: ...

2020-11-24 · 2 分钟 · 350 字 · 涯余