标准C中strtok函数分割字符串
2013-04-25 22:29
309 查看
标准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<stdio.h>
2 #include<string.h>
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
函数为: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<stdio.h>
2 #include<string.h>
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
相关文章推荐
- C/C++_字符串分割strtok函数
- 用strtok函数分割字符串
- LoadRunner中使用strtok函数分割字符串
- C语言利用strtok函数实现字符串自由分割
- strtok函数的妙用,分割字符串
- 【摘录】C语言中利用 strtok函数进行字符串分割
- 标准C++字符串string任意分割
- c++ 字符串分割一、用strtok函数进行字符串分割 原型: char *strtok(char *str, const char *delim); 功能:分解字符串为一组字符串。 参数说明:
- strtok函数字符串分割
- strtok函数实现字符串分割
- C语言分割字符串strtok函数
- 编写一段程序,从标准输入中读取多个字串并将他么连接起来,输出成大的字符串。 改写上述程序,用空格把输入的多个字符串分割开来。
- strtok函数分割字符串
- strtok函数分割字符串
- 标准C++ 与MFC 6.0 中字符串的分割
- C语言标准字符串分割
- C 语言 分割字符串 strtok函数
- 标准C中strtok函数分割字符串
- 标准std::string分割字符串split
- 标准C++ 与MFC 6.0 中字符串的分割