C语言分割平衡字符串递归,用C实现字符串分割并返回全部子串

用C实现字符串分割并返回所有子串

#include

#include

#include

#include

char ** split(char *mother, char split_char)

{

char *arry[1024]; //the MAX sub string is 1024 and you can modify it

char *new;

char buf[1024] = {'\0'};

int len, i, j, k, len_sub;

for(i = 0, j = 0, k = 0; i < strlen(mother); i++) //scan the string "mother" to split by "split_char"

{

if(mother[i] == split_char)

{

len_sub = strlen(buf);

printf("sub len is %d\n", len_sub);

if(len_sub > 0)

{

printf("buf str is %s\n", buf);

new = (char *)malloc(len_sub);

strcpy(new, buf);

arry[j] = new;

printf("arry[%d] = %s\n", j, arry[j]);

j++;

memset(buf, '\0', sizeof(buf));

k = 0;

continue;

} else{

continue;

}

}

if(mother[i] != split_char)

{

buf[k] = mother[i];

k++;

}

if((strlen(mother) - 1) == i && strlen(buf) != 0)

{

printf("the last str is made \n");

printf("buf str is %s\n", buf);

len_sub = strlen(buf);

printf("sub len is %d\n", len_sub);

new = (char *)malloc(len_sub);

if(new == NULL)

{

printf("malloc error\n");

}

strcpy(new, buf);

printf("j = %d\n", j);

arry[j] = new;

memset(buf, '\0', sizeof(buf));

printf("arry[%d] = %s\n", j, arry[j]);

j++;

memset(buf, '\0', sizeof(buf));

}

}

new = (char *)malloc(1); //ened indication in the str arry

new[0] = '\0';

arry[j] = new;

i = 0;

printf("in split func print result as below:\n");

while(strlen(arry[i]))

{

printf("%s\n",arry[i]);

i++;

}

printf("ened print\n");

return arry;

}

int main(void)

{

char *s = "abc def ghi jkl mno";

char **ss;

int i;

ss = split(s, ' ');

i = 0;

printf("in main func print result as below:\n");

while(strlen(ss[i]))

{

printf("%s\n",ss[i]);

i++;

}

printf("ened print\n");

return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值