strtok什么函数
时间: 2024-04-13 22:21:39 浏览: 19
strtok函数是一个字符串函数,用于将一个字符串分解为一组字符串。它的函数原型如下:
```c
char *strtok(char s[], const char *delim);
```
其中,s是要分解的字符串,delim是分隔符字符串。strtok函数会将s按照delim中的字符进行分割,并返回分割后的第一个子字符串的指针。之后每次调用strtok函数时,传入NULL作为第一个参数,函数会继续返回下一个子字符串的指针,直到所有子字符串都被返回完毕。
例如,对于字符串"hello,hi:what?is!the....",可以使用strtok函数按照逗号、冒号、问号和感叹号进行分割,示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello,hi:what?is!the....";
const char delim[] = ",:?!";
char *token;
token = strtok(str, delim);
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, delim);
}
return 0;
}
```
运行以上代码,输出结果为:
```
hello
hi
what
is
the
```
注意:strtok函数会修改原始字符串,将分隔符替换为字符串结束符'\0'。如果需要保留原始字符串,可以使用strtok_r函数。