c语言通过字符串头对数组进行分割
时间: 2023-07-25 09:23:12 浏览: 96
C语言中可以使用字符串头文件 `<string.h>` 中的函数 `strtok()` 来对数组进行分割。`strtok()` 函数是一个字符串分割函数,它可以将字符串按照指定的分隔符分割成多个子字符串。
下面是一个简单的例子,我们将字符串 `"hello world, I am here"` 按照空格和逗号进行分割:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world, I am here";
char *tok = strtok(str, " ,");
while (tok != NULL) {
printf("%s\n", tok);
tok = strtok(NULL, " ,");
}
return 0;
}
```
运行结果如下:
```
hello
world
I
am
here
```
在上面的例子中,首先我们定义了一个字符串 `str`,然后使用 `strtok()` 函数对它进行分割,分隔符为空格和逗号。`strtok()` 函数首次调用时,第一个参数传入需要分割的字符串,第二个参数传入分隔符字符串。调用成功后,函数返回第一个子字符串的指针。接下来,我们使用 while 循环不断调用 `strtok()` 函数,直到返回值为 `NULL`,表示所有子字符串都已经分割完毕。每次调用 `strtok()` 函数时,第一个参数传入 `NULL`,表示继续分割上一个字符串的剩余部分,第二个参数不再传入分隔符字符串。最后,我们将每个子字符串输出到控制台上。
阅读全文
相关推荐


















