strtok函数是字符串函数库中的一个函数,函数原型如下:
char *strtok(char s[], const char *delim);
作用:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。
例如:"hello,hi:what?is!the.matter;" 把这串字符串传入strtok函数,第二个delim写 ",:?!.;" , 这样就可以得到6个不同的子字符串。
我们来写个例子验证一下,就写分割时间的例子吧,借用这个博客:http://blog.csdn.net/luoweifu/article/details/20288549写的获取UTC时间的例子,将它改一下:
修改如下:
#include <stdio.h>
#include <string.h>
#include <time.h>
int main()
{
char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
struct tm *p;
char buf[100] = {0};
char *q ;
time_t timep;
time(&timep); /*获得time_t结构的时间,UTC时间*/
p = gmtime(&timep); /*转换为struct tm结构的UTC时间*/
sprintf(buf,"%d/%d/%d-%s-%d:%d:%d\n",
1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday,
wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);
printf("%s\n",buf);
q = strtok(buf,"//--::");
printf("q : %s\n",buf);
while(1)
{
q = strtok(NULL ,"//--::");
if(q == NULL)
break ;
printf("q : %s\n",q);
}
return 0;
}
运行结果:
2017/8/17-Thu-8:24:43
q : 2017
q : 8
q : 17
q : Thu
q : 8
q : 24
q : 43