博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C语言的字符串分割
阅读量:6982 次
发布时间:2019-06-27

本文共 1307 字,大约阅读时间需要 4 分钟。

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

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.   
  3.    result is "now "  
  4.    result is " is the time for all "  
  5.    result is " good men to come to the "  
  6.    result is " aid of their country" 
这个函数跟编译器中的词法分析很像,在以后的文本处理中,会解决很多问题。看来我有必要系统的学习下C的库函数,而不仅仅是死扎在语法和一些算法技巧上面。这样在平常的工作中才能事半功倍。
使用这个函数,形如下面的配置文件就非常容易解析:
id1 value1 value2 value3
id2 value1 value2 value3
...
使用这个函数,分割字符串就更加方便了,例如下面待分割的字符串:
12|2345|asld|alsfalskd
只要读取待处理的数据,然后调用四次strtok就能够解析出每行的值,以前我一般不是自己解析就是用sscanf,但是strtok更加合适,也更加啊灵活! 推荐:

转载地址:http://yntpl.baihongyu.com/

你可能感兴趣的文章
传神成进博会唯一指定智能翻译硬件提供商 力助无障碍沟通
查看>>
微信小程序实现slideUp、slideDown滑动效果及点击空白隐藏功能示例
查看>>
Java程序员须知:分布式微服务为什么很难?
查看>>
SQLServer之创建唯一聚集索引
查看>>
好程序员web前端技术之CSS3过渡
查看>>
java B2B2C源码电子商务平台 - Zuul回退机制
查看>>
记录Docker in Docker 安装(CentOS7)
查看>>
简单的写一个发布订阅器
查看>>
重学前端-js的类型问题
查看>>
Function类型
查看>>
Python学习
查看>>
你有多渴望赚钱
查看>>
ES6之let和const
查看>>
关于跨域
查看>>
一个半路出家的前端工程师的2018 | 掘金年度征文
查看>>
Fork/Join 框架介绍
查看>>
topK问题
查看>>
5.6 前端开发日报
查看>>
数据库的使用你可能忽略了这些 (续)
查看>>
面试官:聊一下你对MySQL索引实现原理?
查看>>