1、strtok原型与应用
原型:char *strtok(char *src, const char *delim);
功能:将src(原字符串)根据delim(分隔符串)分解为不同子串(连续算一个)
返回:属于当前分割的子串,当前没有分割的子串时返回NULL
#include <stdio.h>
#include <string.h>
int main(void) {
char s[] = "hello, world! welcome to china!";
char delim[] = " ,!";
char *token;
for(token = strtok(s, delim); token != NULL; token = strtok(NULL, delim)) {
printf(token);
printf("+");
}
printf("\n");
return 0;
}
输出:hello+word+welcome+to+china+
2、strsep原型与应用
原型:char *strsep(char * src; const char *delim);
功能:将src(原字符串)根据delim(分隔符串)分解为不同的子串(分隔符串一对一替换)
返回:属于当前分割的子串,当前没有分割的子串时返回NULL
#include <stdio.h>
#include <string.h>
int main(void) {
char source[] = "hello, world! welcome to china!";
char delim[] = " ,!";
char *s = strdup(source);
char *token;
for(token = strsep(&s, delim); token != NULL; token = strsep(&s, delim)) {
printf(token);
printf("+");
}
printf("\n");
return 0;
}
输出:hello++word++welcome+to+china+;
注:主要区别在分隔符串如果是多个字符组成且在原字符串中是连续出现的话(例delim, 原字符串中有连续的", ","! "),strtok一次统一替换为一个'\0',而strsep会挨个替换,且几个分割字符连续的话他会挨个返回空字符串,如“”,因此如果需要使用strsep的话必须要做返回值为空串的判断。