/*********************************************
* @brief 将字符串按照指定子串分割,逐个返回分割后的 token
* @param str 被分割的字符串
* @param delim 用于分割的子串
* @return 下一个 token 的地址
********************************************/
char* strtok(char* restrict str, const char* restrict delim);
!subtitle:说明
将字符串按照指定子串分割,逐个返回分割后的 token。
注意:
这个函数是破坏性的,它会将源字符串 str 中的分割字符串 delim 的首字母修改为 '\0'。
这个函数是线程不安全的,它使用静态变量标记下一次返回 token 的位置
!subtitle:参数
str - 被分割的字符串
获取下一个 token 时,此参数传 NULL
delim - 用于分割的子串
!subtitle:返回值
下一个 token
#include <stdio.h>
#include <string.h>
int main(void)
{
char text[] = "Pandas are very cute"; // 被分割的字符串
const char* delim = " "; // 通过空格进行分割
char* token = strtok(text, delim); // 首次调用时传递完整参数,返回第一个 token
while(token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, delim); // 后续调用时第一个参数传递 NULL,逐次返回 token
}
return 0;
}
说明:
通过 strtok 查找空格及标点符号,从而实现单词的分割提取。
运行结果:
Pandas
are
very
cute
C23 standard (ISO/IEC 9899:2024):
7.24.5.8 The strtok function (p: TBD)
C17 standard (ISO/IEC 9899:2018):
7.24.5.8 The strtok function (p: TBD)
C11 standard (ISO/IEC 9899:2011):
7.24.5.8 The strtok function (p: 369-370)
C99 standard (ISO/IEC 9899:1999):
7.21.5.8 The strtok function (p: 332-333)
C89/C90 standard (ISO/IEC 9899:1990):
4.11.5.8 The strtok function