主要使用 strtok()函数实现
#include
char *strtok(char *str, const char *delim);
char *strtok_r(char *str, const char *delim, char **saveptr);
其中strtok() 非线程安全;
strtok_r 线程安全。
sample code
#include
#include
#include
void strSplit()
{
char str[]={"on:[0.000005,1.211111],[5.000005,6.211111]"};
char *p = strtok(str+3, ",");
printf("00----%s\n",p);
printf("000----%s\n",str);
int i = 0;
while(p)
{
p = strtok(NULL, ",");
printf("i:%d -- %s\n", ++i, p);
}
}
void strSplit1()
{
char str[]={"on:[0.000005,xxx]"};
char *p = strtok(str+3, ",");
printf("00----%s\n",p);
printf("00----%s (%f)\n",p, atof(p+1));
printf("00----%s (%f)\n",p, atof(p));
if(p)
{
p = strtok(NULL, ",");
// printf("01----%s , %ld\n",p, strlen(p));
// p[strlen(p)-1] = '\0';
printf("01----%s (%f)\n",p, atof(p));
}
}
小彩蛋:
使用atof() 时,会自动去除数字字符后的非数字字符; 但是如果数字字符前面带有非数字字符就会直接返回0.