字符串拆分,根据指定分隔符拆分字符串

有时需要根据指定内容,完成对字符串的拆分,针对这个需求,将字符串函数进行整合,完成了拆分字符串的功能

比如:我们有一组数据 "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;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值