有时需要根据指定内容,完成对字符串的拆分,针对这个需求,将字符串函数进行整合,完成了拆分字符串的功能
比如:我们有一组数据 "SPLITxxLINExxTOxxARRAY",中间有固定分隔字符串xx,运行下面子函数,就能获得字符串数据 SPLIT、LINE、TO、ARRAY。
注意:拆分完成的字符串数组是由此函数完成空间分配,因此,在使用完成后,注意释放对应空间
/* 根据指定字符串拆分字符串 */
/* 输入值:字符串,分隔字符串 */
/* 输出值:分隔段数,分隔后字符串数组 */
int SplitLineToArray(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;
}