在 C 语言 中 strtok 函数 用于根据分界符将 字符串 分割成一个个片段。
char *strtok(char *str, const char *delim);
参数 | 描述 |
---|---|
str | 要被分解成一组小字符串的字符串。 |
delim | 包含分隔符的 C 字符串。 |
该函数返回被分解的第一个子字符串,如果没有可检索的字符串,则返回一个空指针。
使用 strtok 函数,需要引入 string.h 头文件。
使用 strtok() 函数,实现分割字符串
#include <stdio.h>
#include <string.h>
int main()
{
printf("嗨客网(www.haicoder.net)\n\n");
char str[] = "Hello,HaiCoder,Hello,World";
const char s[2] = ",";
char *token;
// 获取第一个子字符串
token = strtok(str, s);
/* 继续获取其他的子字符串 */
while ( token != NULL )
{
printf("Str = %s\n", token);
token = strtok(NULL, s);
}
return 0;
}
程序运行后,控制台输出如下:
我们首先,定义了一个字符串 str,接着,定义了一个字符串分隔符变量 s,最后,我们使用了 strtok 在字符串 str 中以分隔符 s 来分割该字符串。
最后,我们使用 while 循环 判断分割的字符串不是 NULL,那么就继续分割,从而分割出了所有的字符串。
在 C 语言中 strtok 函数用于根据分界符将字符串分割成一个个片段。