split.c / C /* (C)hg 2009 Filename : split.c Compiler : Visual C++ 9.0 Description : Demo how to implement split() in C Release : 05/09/2009 1.0 */ #include <stdio.h> #include <string.h> void split(char **arr, char *str, const char *del) { char *s = strtok(str, del); while(s != NULL) { *arr++ = s; s = strtok(NULL, del); } } int main() { char *str = "10,20,30"; char *arr[3]; const char *del = ","; int i = 0; split(arr, str, del); while(i<3) printf("%s\n", *(arr+i++)); }
寫過JavaScript或其他语言,應該常常用到split()這個函數,他可以輕易地將string轉成array,C語言並沒有相對應的函數,只有strtok()較為接近,稍微加工後,就可以在C語言實現split()。