C语言——按照指定分割符分割字符串

函数作用 : 分割字符串

/**********************************************************************
* Function:  split_str
* Description: Splits the target string by the specified character 
* Input:  
		psrc:		Pointer to the data to be processed
		psrc_len:	The length of the data to be processed
		sign:		Separator
		pdest:		Pointer to store the result of the partition	
		pdest_len:	Store split result size		
* Return:  Number of segmentation results
* Others:  When calling this function, remember to use free_space function releases space. pdest is a pointer array.
* Modify Date    Version    Author       Modification
* -----------------------------------------------
* 2021/03/04     V1.0       czw          
**********************************************************************/
int split_str(const char *psrc,int psrc_len,char sign,char **pdest,int pdest_len)
{
    
    
	if(NULL == psrc || NULL == pdest)
	{
    
    
		return 0;
	}
	
	int i = 0;
	int result = 0;
	int start = 0,end = 0;
	int len = 0;
	
	for(i = 0;i < psrc_len;i++)
	{
    
    
		if(psrc[i] == sign)
		{
    
    
			end = i;
			len = end - start;
			pdest[result] = (char *)malloc(len+1);
			if(pdest[result] != NULL)
			{
    
    
				memcpy(pdest[result],psrc+start,len);
				pdest[result][len] = '\0';
				result++;
				start = end+1;
			}else
			{
    
    
				return result;
			}
		}
		
	}
	
	if(start != psrc_len)
	{
    
    
		len = psrc_len-start;
		pdest[result] = (char *)malloc(len+1);
		if(pdest[result] != NULL)
		{
    
    
			memcpy(pdest[result],psrc+start,len);
			pdest[result][len] = '\0';
			result++;
			start = end+1;
		}else
		{
    
    
			return result;
		}		
	}
	return result;
}
/**********************************************************************
* Function:  free_space
* Description: release space
* Input: 
		pdest:		An array of Pointers to be freed	
		pdest_len:	array size		
* Return:  None
* Others:  
* Modify Date    Version    Author       Modification
* -----------------------------------------------
* 2021/03/04     V1.0       czw          
**********************************************************************/
void free_space(char **pdest,int pdest_len)
{
    
    
	if(pdest == NULL)
		return;
	int i = 0;
	for(i = 0;i < pdest_len;i++)
	{
    
    
		if(pdest[i] != NULL)
		{
    
    
			free(pdest[i]);
		}
	}
	return;
}

示例

int main(int argc,char *argv[])
{
    
    
	char *dest[50];
	char test[500];
	int result = 0;
	int i = 0;
	while(1)
	{
    
    
		memset(test,0x00,sizeof(test));
		printf("输入分割字符:");
		scanf("%s",test);
		if(strcmp(test,"bye") == 0)
			break;
		result = split_str(test, strlen(test),'|',dest,sizeof(dest)/sizeof(char *));
		for(i = 0;i < result;i++)
		{
    
    
			printf("第%d组 = %s\n",i,dest[i]);
		}
	}

	free_space(dest,sizeof(dest)/sizeof(char *));
	return 0;
}

结果
在这里插入图片描述
代码有错误请留言

猜你喜欢

转载自blog.csdn.net/qq_41290252/article/details/114376586