c语言的字符串分解——strtok函数和strsep函数
来源:互联网 发布:雪梨的淘宝店 编辑:程序博客网 时间:2024/04/28 10:23
转自《http://c.chinaitlab.com/skill/871101.html》
今天才知道原来C语言也有类似java的split的函数,按特定字符串对字符串进行分解:
strtok的解释和示例:
strtok
Syntax:
view plain
<span style="font-size:16px;">#include <cstring> char *strtok( char *str1, const char *str2 );</span>
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:
view plain
<span style="font-size:16px;"></span><pre name="code" class="cpp"> 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:
view plain
<span style="font-size:16px;">result is "now "
result is " is the time for all "
result is " good men to come to the "
result is " aid of their country" </span>
在s中找出以ct中的字符为分隔的字符串,即是源串中除去了含有分隔串中的所有字符后余下的一段段的字符串,每调用一次找到一串,找不到则返回空串。第一次调用必须传给它有效的字符串,第二次传NULL就可以了,每次调用返回找到的子串的时候都会把源串中该子串的尾部字符(原来是搜索串中的某一字符)修改成'/0'字符返回值为每次调用得到的字串。
但是百度百科里面又有提到说“最新的Linux内核2.6.29,说明了这个函数已经不再使用,由速度更快的strsep()代替”。所以又去查了下strsep函数:
原型:char *strsep(char **stringp, const char *delim);
功能:分解字符串为一组字符串。从stringp指向的位置起向后扫描,遇到delim指向位置的字符后,将此字符替换为NULL,返回stringp指向的地址。
但是strsep函数,在 Windows是没有支持的,我是在Linux环境,所以ok~
给个例子:
view plain
char str2[] = "2011/11/28";
char *buf;
char *token;
buf = str2;
while((token = strsep(&buf, "/")) != NULL){
printf("%s\n", token);
}
输出:
view plain
2011
11
28
- c语言的字符串分解——strtok函数和strsep函数
- c语言的字符串分解——strtok函数和strsep函数
- c语言的字符串分解——strtok函数和strsep函数
- 字符串分割函数---strtok和strsep函数
- strtok和strsep函数详解
- strtok和strsep函数详解
- strtok和strsep函数详解
- strtok和strsep函数详解
- strtok和strsep函数详解
- strtok和strsep函数详解
- strtok和strsep函数详解
- 字符串分割函数strtok和strsep使用注意事项
- 字符串分割函数StringTokenizer与strtok,strsep的比较
- C 拆分字符串(strtok,strsep)
- strsep 函数 c 语言 实现
- C语言 strsep函数实现
- strtok 与 strsep 函数说明
- strtok 与 strsep 函数说明
- opencv 浮雕操作
- putty中文乱码 终极解决方案(抱歉之前上传的还是乱码,现已修正,现免积分下载)
- Linux 目录说明
- A Simple Problem with Integers----HDU_3468----线段树之成段更新
- 让人抓狂匪夷所思的4组代码
- c语言的字符串分解——strtok函数和strsep函数
- opencv 雕刻操作
- Sentiment Classification调研
- 当form里增加enctype="multipart/form-data"时,上传文件与其他表单数据的研究
- win7 安装U872 MDAC版本解决办法(New)
- c,c++里面,头文件里面的ifndef /define/endif的作用
- 禁用Enter键表单自动提交
- 利用判断view的高度来关闭输入法
- HTML5一步一步走——独立数据存储