C语⾔的字符串分割
说起来很有意思,⾃认为对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
...
使⽤这个函数,分割字符串就更加⽅便了,例如下⾯待分割的字符串:
字符串截取c语言12|2345|asld|alsfalskd
只要读取待处理的数据,然后调⽤四次strtok就能够解析出每⾏的值,以前我⼀般不是⾃⼰解析就是⽤sscanf,但是strtok更加合适,也更加啊灵活!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论