歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 標准C中strtok函數分割字符串

標准C中strtok函數分割字符串

日期:2017/3/1 9:58:01   编辑:Linux編程

標准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

Copyright © Linux教程網 All Rights Reserved