码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-01-22 12:35:56      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

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;
}

 

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

标签:

原文地址:http://www.cnblogs.com/brave-firm/p/4241257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!