1.
char *strtok(char *str, const char *delim) 头文件#include<string.h>
str要分割的字符串,delim分隔符(字符串以什么分割)
int main()
{
const char *str = "hello world 123";
char *buf[3];
int i = 0;
分割同一字符串,第一次调用时传入字符串的首地址,第二个参数是分割符
char*p = strtok(str, " ")
while(p)
{
buf[i++] = p;
// 再次调用分割时指针要变为NULL, 也就是这里的第一个参数,分割的字符串还是str
// 第二个参数要和第一次调用时的分割符保持一致
p = strtok(NULL, " ")
}
for (i = 0; i < 3; ++i)
{
printf("%s\n", buf[i]);
}
return 0;
}
2.
int sscanf(const char *str, const char *format, ...) 头文件#include<stdio.h>
用sscanf()分割字符串的话,只能以空格分割字符串
str要分割的字符串,format,输出格式,后面的参数为分割后的字符串存储地址
#include<stdio.h>
int main()
{
const char *buf = "hello world 133";
char a[10], b[10];
int c;
sscanf(buf, "%s %s %d", a, b, &c);
printf("%s\n%s\n%d\n", a, b, c);
return 0;
}