使用C語言實現字串分割
阿新 • • 發佈:2018-12-17
之前分享了一篇使用C++(std::string 作為容器)進行字串分割的博文:
https://blog.csdn.net/r5014/article/details/82802664
現在又想用C語言做一個字串分割的函式,大概功能是這樣:
需要分割的字串“ this is a charactor raw. ” 使用 ' '分割
分割之後會返回一個char** strv 表示分割出子串str的vector,返回一個int strc表示分割出子串的數量,在使用完畢之後自行釋放strv
strv可能是NULL 比如" "使用‘ ’分割之後就是NULL。
以下介紹分割函式splitstr_c()
//* 切割字串,strv返回字串陣列,strc返回分割之後的字串數量 void splitstr_c(char* str, char c, char*** strv, int* strc) { int i = 0; int j = 0; int n = 0; int offset_strv = 0; int offset_font = 0; int offset_back = 0; int str_size = strlen(str); char** tstrv = NULL; for(i = 0; i < str_size; i++) { if(i > 0) { if((str[i] != c) && (str[i - 1] == c)) { n++; } } else { if(str[0] != c) { n++; } } } if(n == 0) { for(i = 0; i < str_size; i++) { if(str[i] != c) { n++; break; } } } * strc = n; tstrv = (char**)malloc(sizeof(char*) * n); memset(tstrv, 0, sizeof(char*)*n); for(i = 0; i < str_size; i++) { if(str[i] == c) { offset_back = i; if(offset_back != offset_font) { n = offset_back - offset_font; char* sub_str = (char*)malloc(sizeof(char) * (n + 1)); //* n + 1是為了容納'\0' memset(sub_str, 0, sizeof(char) * (n + 1)); memcpy(sub_str, str + offset_font, n); tstrv[offset_strv] = sub_str; offset_strv++; } offset_font = offset_back + 1; } } if(offset_back < str_size) { offset_back = str_size; if(offset_back != offset_font) { n = offset_back - offset_font; char* sub_str = (char*)malloc(sizeof(char) * (n + 1)); memset(sub_str, 0, sizeof(char) * (n + 1)); memcpy(sub_str, str + offset_font, n); tstrv[offset_strv] = sub_str; offset_strv++; } offset_font = offset_back + 1; } * strv = tstrv; }
順帶給出兩個小工具函式:
//* print strv void print_strv(char** strv, int strc) { if(strc > 0) { for(int i = 0; i < strc; i++) { printf("%s\n",strv[i]); } } } //* strv使用完之後根據strc來進行釋放。 void free_strv(char** strv, int strc) { if(strc > 0) { for(int i = 0; i < strc; i++) { //printf("%s\n",strv[i]); free(strv[i]); } free(strv); } }
讓我們來試一下:
char *text = " this is a charactor text. ";
//char *text = "000this00is0a0charactor0text.00";
//char *text = "this is a charactor text.";
//char *text = "a a a a s ";
char** strv = NULL;
int strc = 0;
splitstr_c(text, ' ', &strv, &strc);
printf("splitstr_c: %d\n", strc);
print_strv(strv, strc);
free_strv(strv, strc);
結果:
自此這個功能就實現了