/**********************************************************************
* 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;
}
C++的解决方法:
vector<string> split(const string& str, const string& pattern)
{
vector<string> ret;
if(pattern.empty()) return ret;
size_t start=0,index=str.find_first_of(pattern,0);
while(index!=str.npos)
{
if(start!=index)
ret.push_back(str.substr(start,index-start));
start=index+1;
index=str.find_first_of(pattern,start);
}
if(!str.substr(start).empty())
ret.push_back(str.substr(start));
return ret;
}