如何通过strtok函数实现字符串分割的示例?

2026-05-08 16:463阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计438个文字,预计阅读时间需要2分钟。

如何通过strtok函数实现字符串分割的示例?

`strtok`函数是C语言字符串函数库中的一个函数,其原型如下:

cchar *strtok(char *s, const char *delim);

作用:将字符串`s`分割成一组字符串,以`delim`中的字符作为分隔符。

`s`是要分割的字符串,`delim`是分隔符字符串。

例如:`hello,hi`

strtok函数是字符串函数库中的一个函数,函数原型如下:

char *strtok(char s[], const char *delim);

作用:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。

例如:"hello,hi:what?is!the.matter;" 把这串字符串传入strtok函数,第二个delim写 ",:?!.;" , 这样就可以得到6个不同的子字符串。

我们来写个例子验证一下,就写分割时间的例子吧,获取UTC时间

如下:

如何通过strtok函数实现字符串分割的示例?

#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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对自由互联的支持。如果你想了解更多相关内容请查看下面相关链接

本文共计438个文字,预计阅读时间需要2分钟。

如何通过strtok函数实现字符串分割的示例?

`strtok`函数是C语言字符串函数库中的一个函数,其原型如下:

cchar *strtok(char *s, const char *delim);

作用:将字符串`s`分割成一组字符串,以`delim`中的字符作为分隔符。

`s`是要分割的字符串,`delim`是分隔符字符串。

例如:`hello,hi`

strtok函数是字符串函数库中的一个函数,函数原型如下:

char *strtok(char s[], const char *delim);

作用:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。

例如:"hello,hi:what?is!the.matter;" 把这串字符串传入strtok函数,第二个delim写 ",:?!.;" , 这样就可以得到6个不同的子字符串。

我们来写个例子验证一下,就写分割时间的例子吧,获取UTC时间

如下:

如何通过strtok函数实现字符串分割的示例?

#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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对自由互联的支持。如果你想了解更多相关内容请查看下面相关链接