C語言字串分割函式split實現
阿新 • • 發佈:2019-01-07
#include <stdlib.h> #include <string.h> #include <stdio.h> /* 用delimiter中的每一個分隔符分割str字串,這並不會改變str中的字元,然後返回一個字串陣列. 字串陣列中的字串有可能是以'\0'開頭的空串(出現在str首尾或連續的分隔符會產生這樣的空串). 這個函式有以下特性: 支援多執行緒,可重入的; 不會修改原字串; 能處理首尾和連續的分隔符. 返回:以NULL為結束標誌的字串陣列. */ char** split(char *str, char *delimiter) { int len = strlen(str); char *strCopy = (char*)malloc((len + 1) * sizeof(char)); //額外分配多一個字元空間來儲存'\0' strcpy(strCopy, str); //複製str字串 //將strCopy中的每個分隔符賦值為'\0' for (int i = 0; strCopy[i] != '\0'; i++) { for (int j = 0; delimiter[j] != '\0'; j++) { if (strCopy[i] == delimiter[j]) { strCopy[i] = '\0'; break; } } } //為字串陣列分配空間,額外分配多一個字串指標並賦值為NULL來作為字串結束標誌 char** res = (char**)malloc((len + 2) * sizeof(char*)); len++; //遍歷到strCopy最後的'\0'才結束 int resI = 0; //每一個分隔符和原字串的'\0'標誌依次作為陣列中的字串的結束標誌 for (int i = 0; i < len; i++) { res[resI++] = strCopy + i; while (strCopy[i] != '\0') { i++; } } res[resI] = NULL; //字串陣列中結束標誌 return res; } int main() { //split測試資料 char strs[][40] = { {""}, {"apple"}, {"
[email protected]"}, {"[email protected]&e"}, {"@"}, {"[email protected]@le"}, {"@[email protected]"} }; for (int i = 0; i < 7; i++) { char **res = split(strs[i], (char*)"@&"); for (int j = 0; res[j] != NULL; j++) { printf("%s\n", res[j]); } printf("**************\n"); } return 0; }
測試效果: