函数原型
#include <string.h>
char *strtok(char *str, const char *delim);
char *strtok_r(char *str, const char *delim, char **saveptr);
-
str: 要分割的字符
-
delim: 分隔符
-
saveptr: str分割后的后部分
-
返回值: str分割后的后部分,如果没有满足的条件的则返回NULL
例子
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char *saveptr;
char *s;
char arr[50] = "hello,world,color";
char *buf = arr;
//char *buf = "hello,world,color"; /* crash coredump */
char *dem = ",";
while((s = strtok_r(buf, dem, &saveptr)) != NULL){
if ( s != NULL && saveptr != NULL){
printf("s=%s saveptr=%s\n", s, saveptr);
buf = NULL;
}
}
return 0;
}
注意这里buf不能直接是char *buf = "hello,world,color"
,会crash的
# ./a.out
s=hello saveptr=world,color
s=world saveptr=color
s=color saveptr=
标签:字符,分割,strtok,color,saveptr,char,NULL,buf
From: https://www.cnblogs.com/tangshunhui/p/16639235.html