#include <stdio.h> #include <stdlib.h> #include <string.h> /* 字符串切割函數 */ /* 知識補充: 1. 函數原型: char *strtok(char *str, const char *delim); char *strsep(char **stringp, const char *delim); 2. 功能: strtok和strsep兩個函數的功能都是用來分解字符串爲一組字符串。str爲要分解的字符串,delim爲分隔符字符串。 3. 參數說明: str(stringp)要求不能夠是 const char *,由於 strtok 或者 strsep 都會修改 str 的值(修改指針的值) delim 能夠多個字符的集合,strtok(strsep)會按單個字符切割子串 4. 返回值: 從str開頭開始的第一個子串,當沒有分割的子串時返回NULL。 5. 相同點: 二者都會改變源字符串,想要避免,能夠使用strdupa(由allocate函數實現)或strdup(由malloc函數實現)。 6. 不一樣點: a. strtok函數第一次調用時會把s字符串中全部在delim中出現的字符替換爲NULL。而後經過依次調用strtok(NULL, delim)獲得各部分子串。 b. strsep函數第一次調用時會把s字符串中全部在delim中出現的字符替換爲'\0'。而後經過依次調用strtok(stringp, delim)獲得各部分子串。 c. strsep在切割字符串的過程當中,可能屢次返回空字符串('\0'),可是 strtok 只會在結束時才返回 NULL d. strtok 內部記錄上次調用字符串的位置,因此不支持多線程,可重入版本爲strtok_r e. strsep支持多線程 */ void test() { char p[] = "hello this world . the world is good ."; char *pcIndex = p; char *token = NULL; while (token = strsep(&buf, ". "), token) { //*token 可能會等於 '\0' if (*token) { printf("--[%s]---[%p]---buf[%p]--\n", token, token, buf); } } } int main() { test(); return 0; }