
- C 标准库
- C 库 - 首页
- C 库 - <assert.h>
- C 库 - <complex.h>
- C 库 - <ctype.h>
- C 库 - <errno.h>
- C 库 - <fenv.h>
- C 库 - <float.h>
- C 库 - <inttypes.h>
- C 库 - <iso646.h>
- C 库 - <limits.h>
- C 库 - <locale.h>
- C 库 - <math.h>
- C 库 - <setjmp.h>
- C 库 - <signal.h>
- C 库 - <stdalign.h>
- C 库 - <stdarg.h>
- C 库 - <stdbool.h>
- C 库 - <stddef.h>
- C 库 - <stdio.h>
- C 库 - <stdlib.h>
- C 库 - <string.h>
- C 库 - <tgmath.h>
- C 库 - <time.h>
- C 库 - <wctype.h>
- C 标准库资源
- C 库 - 快速指南
- C 库 - 有用资源
- C 库 - 讨论
C 库 - strtok() 函数
C 库的 strtok() 函数用于将字符串分割成标记。这些字符串使用分隔符/分隔字符设置一组标记。通常,标记通常是字符串中的单词、短语或单个字符。
这里,char *strtok(char *str, const char *delim) 使用分隔符 delim 将字符串 str 分割成一系列标记。
语法
以下是 C 库 strtok() 函数的语法:
char *strtok(char *str, const char *delim)
参数
此函数接受以下参数:
str − 此字符串的内容将被修改并分解成较小的字符串(标记)。
delim − 这是包含分隔符的 C 字符串。这些分隔符在每次调用之间可能会有所不同。
返回值
此函数返回指向在字符串中找到的第一个标记的指针。如果没有剩余标记可检索,则返回空指针。
示例 1
以下是说明 strtok() 函数用法的 C 程序。
#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); }
输出
执行上述代码后,我们将得到以下结果:
This is www.tutorialspoint.com website
示例 2
在此示例中,我们演示了如何使用 strtok() 函数将字符串的每个子字符串在新的一行中表示。
#include <stdio.h> #include <string.h> int main() { char stng[100] = "Welcome to C Programming"; char *res; res = strtok(stng, " "); while(res != NULL) { printf("%s \n", res); res = strtok(NULL, " "); } return 0; }
输出
执行上述代码后,结果将是:
Welcome to C Programming
示例 3
以下是演示如何使用 strtok() 函数返回空指针的 C 程序。
#include <stdio.h> #include <string.h> int main() { //String i.e. break in token char str_1[] = "ttttt"; //delimiter char *str_2 = "tp"; // initial call of strtok char *token = strtok(str_1, str_2); printf("The resultant token is %s\n", token); return 0; }
输出
上述代码将产生以下结果:
The resultant token is (null)
广告