功能:按一個字符來拆分字符串
參數 src:要拆分的字符串
參數 delim:按照這個字符來拆分字符串
參數 istr:借助這個結構體來返回給調用者拆分後的字符串數組和字符串的個數
返回拆分是否成功
#include#include #include typedef struct { char **str; //the PChar of string array size_t num; //the number of string }IString; /** Split string by a char * * param src:the string that you want to split * param delim:split string by this char * param istr:a srtuct to save string-array's PChar and string's amount. * eturn whether or not to split string successfully * */ int Split(char *src, char *delim, IString* istr)//split buf { int i; char *str = NULL, *p = NULL; char **data; (*istr).num = 1; str = (char*)calloc(strlen(src)+1,sizeof(char)); if (str == NULL) return 0; data = (char**)calloc(1,sizeof(char *)); if (data == NULL) return 0; str = src; data[0] = strtok(str, delim); for(i=1; p = strtok(NULL, delim); i++) { (*istr).num++; data = (char**)realloc(data,(i+1)*sizeof(char *)); if (data == NULL) return 0; data[i] = p; } (*istr).str = data; free(str); //free(data); //You must to free it in the caller of function str = p = NULL; return 1; } int main() { int i; char s[]=data0|data1|data2|data3|data4|data5|data6|data7|data8; IString istr; if ( Split(s,|,&istr) ) { for (i=0;i 運行結果:
data0 data1 data2 data3 data4 data5 data6 data7 data8