字串拆分,根據指定分隔符拆分字串
阿新 • • 發佈:2019-01-05
有時需要根據指定內容,完成對字串的拆分,針對這個需求,將字串函式進行整合,完成了拆分字串的功能
注意:拆分完成的字串陣列是由此函式完成空間分配,因此,在使用完成後,注意釋放對應空間int ExangeLineToArray(char *line, char *cha, int *index, char ***array) { int length = strlen(line); char *temp1,*temp2; int count=0; int cnt=0; temp1 = (char*)calloc(length+1,sizeof(char)); temp2 = (char*)calloc(length+1,sizeof(char)); strcpy(temp1,line); length = strlen(cha); while(strstr(temp1,cha) != NULL) { temp2 = strstr(temp1,cha); strcpy(temp1,temp2+length); count+=1; } memset(temp1,0,sizeof(temp1)); memset(temp2,0,sizeof(temp2)); *array = (char**)calloc(count+1, sizeof(char*)); for(int i=0;i<count+1;i++) *(*array+i) = (char*)calloc(50,sizeof(char)); strcpy(temp1,line); while(strstr(temp1,cha) != NULL) { temp2 = strstr(temp1,cha); strncpy(*(*array+cnt),temp1,(int)&(temp2[0])-(int)&(temp1[0])); strcpy(temp1,temp2+length); cnt+=1; } if(NULL == strstr(temp1,cha)) strcpy(*(*array+count),temp1); *index = count+1; return 0; }