#include <stdio.h>
#include <string.h>
char* get_sub_str(char* str, int index, char* p_split) ;
int main()
{
char szBuff[1024]="aaa|'|bbb|'||'|ccc";
printf("%s\n", get_sub_str(szBuff, 0, "|'|"));
printf("%s\n", get_sub_str(szBuff, 1, "|'|"));
printf("%s\n", get_sub_str(szBuff, 2, "|'|"));
printf("%s\n", get_sub_str(szBuff, 3, "|'|"));
printf("szBuff=%s\n", szBuff);
return 0;
}
char* get_sub_str(char* src, int index, char* p_split)
{
static char src_temp[1024];
char *p = NULL;
char *p_tmp = NULL;
int i = 0;
int isrc_len = strlen(src);
int isplit_len = strlen(p_split);
memset(src_temp, 0x00 , sizeof(src_temp));
memcpy(src_temp, src, sizeof(src_temp));
p = src_temp;
if (p == NULL || p_split == NULL)
{
return NULL;
}
if (strcmp(src+isrc_len-isplit_len-1, p_split) !=0 )
{
strcat(p, p_split);
}
p_tmp = strstr(p, p_split);
while(p_tmp != NULL)
{
p_tmp [0] = '\0';
if (i == index)
{
return p;
}
p = p_tmp + strlen(p_split);
p_tmp = strstr(p, p_split);
i++;
}
return NULL;
}
输出:
aaa
bbb
ccc
szBuff=aaa|’|bbb|’||’|ccc
Press any key to continue
使用strtok函数也可以根据字符串分隔获取值,但若字段值为空(""),则无法获取;