linux C 根据字符串来分隔源字符串获取各字段值

#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函数也可以根据字符串分隔获取值,但若字段值为空(""),则无法获取;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值