设为首页 加入收藏

TOP

标准C中strtok函数分割字符串
2014-11-24 07:23:47 来源: 作者: 【 】 浏览:0
Tags:标准 strtok 函数分割 字符串

标准C中可以用strtok函数来分割字符串,strtok函数的使用与其他大部分函数的使用方法不同。


函数为:char *strtok(char *strings,const char *tokseps);其中strings为要分割的字符串,tokseps是用来分割的字符。


用以下的例子进行分析:


第6行声明字符串为字符型数组,但当声明为指针型(char *strings = "hello,world!\nwelcome to the earth\")时,编译能够


通过,但是运行时会出现段错误,不知道是什么原因,还要请教一下各位。


第8行tokseps为分隔符,“,”、“\n”、“ ”


第9行pt用来接收分割出来的字符串


注意:strtok函数的返回值是分割后剩下字符串的指针,所以分割出一个子字符串之后,再次调用时要用NULL代替第一个参数


例如第15行。


1 #include
2 #include
3
4 int main()
5 {
6 char strings[] = "hello,world!\nwelcome to the earth\n";
7 puts(strings);
8 char *tokseps = ",\n ";
9 char *pt;
10
11 pt = strtok(strings,tokseps);
12 while(pt)
13 {
14 puts(pt);
15 pt = strtok(NULL,tokseps);
16 }
17
18 return 0;
19 }


输出为:
hello
world!
welcome
to
the
earth


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android 4.2.1短信接收以及应用接.. 下一篇Android 4.2.1短信SMS常用接口整理

评论

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

·python数据分析岗的 (2025-12-25 10:02:21)
·python做数据分析需 (2025-12-25 10:02:19)
·成为一个优秀的pytho (2025-12-25 10:02:16)
·Java后端面试实习自 (2025-12-25 09:24:21)
·Java LTS版本有哪些 (2025-12-25 09:24:18)