C语言 strtok
#include <string.h> char *strtok(char *str, const char *delim);
功能:来将字符串分割成一个个片段。当strtok()在参数s的字符串中发现参数delim中包含的分割字符时, 则会将该字符改为 字符,当连续出现多个时只替换第一个为 。
参数:
- str:指向欲分割的字符串
- delim:为分割字符串中包含的所有字符
返回值:
- 成功:分割后字符串首地址
- 失败:NULL
在第一次调用时:strtok()必需给予参数s字符串
往后的调用则将参数s设置成NULL,每次调用成功则返回指向被分割出片段的指针
案例
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <time.h> int main(void) { // 字符串截取 strtok 会破坏源字符串,会用 替换分隔的标志位 char ch[] = "www.xsk.cn"; // 1、www xsk.cn // 2、www xsk cn // 3、www xsk cn // 1、截取“.”之前内容 char* p = strtok(ch, "."); printf("%s ", p); // 2、打印另外一个标示为 p = strtok(NULL, "."); printf("%s ", p); // 3、打印另外一个标示为 p = strtok(NULL, "."); printf("%s ", p); // 查看内存地址 // printf("%p ", p); // printf("%p ", ch); return 0; }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <time.h> int main(void) { // 截取qq号、保留源邮箱 char ch[] = "21321321@qq.com"; char str[100] = { 0 }; // 字符串备份 strcpy(str, ch); // 截取qq char* p = strtok(str, "@"); printf("%s ", p); // 截取代理邮箱 p = strtok(NULL, "."); printf("%s ", p); return 0; }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <time.h> int main(void) { char ch[] = "woqunimalege bideni kannimabi ageilaozigun "; char* p = strtok(ch, " "); while (p) { printf("%s ", p); p = strtok(NULL, " "); } return 0; }