打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C语言的字符串分割
userphoto

2013.08.16

关注

说起来很有意思,自认为对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 beNULL.

For example:

   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 );
   }            

The above code will display the following output:

   result is "now "
   result is " is the time for all "
   result is " good men to come to the "
   result is " aid of their country"
这个函数跟编译器中的词法分析很向,在以后的文本处理中,会解决很多问题。看来我有必要系统的学习下C的库函数,而不仅仅是死扎在语法和一些算法技巧上面。这样在平常的工作中才能事半功倍。
使用这个函数,形如下面得配置文件就非常容易解析:
id1 value1 value2 value3
id2 value1 value2 value3
...
使用这个函数,分割字符串就更加方便了,例如下面待分割的字符串:
12|2345|asld|alsfalskd
只要读取待处理的数据,然后调用四次strtok就能够解析出每行的值,以前我一般不是自己解析就是用sscanf,但是strtok更加合适,也更加啊灵活!
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C语言对文件的读写操作以及处理CSV文件的方法
C++ split,字符串分割
字符串函数之Strtok()函数
strtok函数的使用
[示例详解]C++常用字符串处理函数及使用
1.?字符串操作函数
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服