字符串按照一定的字符切割

C 庫函數 - strtok()

C 標準庫 - <string.h> C 標準庫 - <string.h>

描述

C 庫函數 char *strtok(char *str, const char *delim) 分解字符串 str 爲一組字符串,delim 爲分隔符。

聲明

下面是 strtok() 函數的聲明。

char *strtok(char *str, const char *delim)

參數

  • str -- 要被分解成一組小字符串的字符串。
  • delim -- 包含分隔符的 C 字符串。

返回值

該函數返回被分解的第一個子字符串,如果沒有可檢索的字符串,則返回一個空指針。

實例

下面的實例演示了 strtok() 函數的用法。

實例

#include <string.h>

#include <stdio.h>

int main ()

{

char str[80] = "This is - www.runoob.com - website"; const char s[2] = "-"; char *token; /* 獲取第一個子字符串 */ token = strtok(str, s);

/* 繼續獲取其他的子字符串 */

while( token != NULL ) {

printf( "%s\n", token );

token = strtok(NULL, s);

}

return(0);

}

讓我們編譯並運行上面的程序,這將產生以下結果:

This is 
 www.runoob.com 
 website
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章