前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C语言的字符串分割

C语言的字符串分割

作者头像
全栈程序员站长
发布2022-07-15 15:20:08
1.8K0
发布2022-07-15 15:20:08
举报

大家好,又见面了,我是全栈君

说起来很有意思,自认为对C语言理解得还是比较深刻的。但居然到今天才知道有个strtok函数,试用了一下突然感慨以前做了多少重复劳动。每次需要解析配置文件,每次需要分割字符串,居然都是自己去分割字符串,既累人又容易出错。感概技术学得不够全面啊!这里引用一段strtok用法:

The strtok() function returns a pointer to the next “token” in str1, where str2 contains the delimiters that determine the token. strtok() returns NULL if no token is found. In order to convert a string to tokens, the first call to strtok() should have str1 point to the string to be tokenized. All calls after this should have str1 be NULL.

For example:

代码语言:javascript
复制
char str[] = "now # is the time for all # good men to come to the # aid of their country";  
   char delims[] = "#";  
   char *result = NULL;  
   result = strtok( str, delims );  
   while( result != NULL ) {  
       printf( "result is \"%s\"\n", result );  
       result = strtok( NULL, delims );  
   }              
/* 何问起 hovertree.com */
  1. The above code will display the following output:
  2. result is “now ”
  3. result is ” is the time for all ”
  4. result is ” good men to come to the ”
  5. result is ” aid of their country”

这个函数跟编译器中的词法分析很像,在以后的文本处理中,会解决很多问题。看来我有必要系统的学习下C的库函数,而不仅仅是死扎在语法和一些算法技巧上面。这样在平常的工作中才能事半功倍。

使用这个函数,形如下面的配置文件就非常容易解析:

代码语言:javascript
复制
id1 value1 value2 value3
id2 value1 value2 value3
...

使用这个函数,分割字符串就更加方便了,例如下面待分割的字符串:

代码语言:javascript
复制
12|2345|asld|alsfalskd

只要读取待处理的数据,然后调用四次strtok就能够解析出每行的值,以前我一般不是自己解析就是用sscanf,但是strtok更加合适,也更加啊灵活!

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/120507.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年12月,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档