设为首页 加入收藏

TOP

C语言的字符串分解——strtok函数和strsep函数
2014-11-24 14:06:09 来源: 作者: 【 】 浏览:0
Tags:语言 字符串 分解 strtok 函数 strsep

原来C语言也有类似java的split的函数,按特定字符对字符串进行分解:


strtok的解释和示例:


strtok


Syntax:


#include char *strtok( char *str1, const char *str2 );


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:


The above code will display the following output:


在str1中找出以str2中出现的字符为分隔的字符串(注:并不是以该字符串为分隔),即是源串中除去了含有分隔串中的所有字符后余下的一段段的字符串,每调用一次找到一串,找不到则返回空串。第一次调用必须传给它有效的字符串,第二次传NULL就可以了,每次调用返回找到的子串的时候都会把源串中该子串的尾部字符(原来是搜索串中的某一字符)修改成'/0'字符返回值为每次调用得到的字串。


但是百度百科里面又有提到说“最新的Linux内核2.6.29,说明了这个函数已经不再使用,由速度更快的strsep()代替”。所以又去查了下strsep函数:


原型:char *strsep(char **stringp, const char *delim);


功能:分解字符串为一组字符串。从stringp指向的位置起向后扫描,遇到delim指向位置的字符后,将此字符替换为NULL,返回stringp指向的地址。


但是strsep函数,在 Windows是没有支持的,我是在Linux环境,所以ok~


给个例子:


输出:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Shell脚本中常用的控制结构 下一篇Java笔试题:HashMap和HashTable..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: