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

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

 

posted on 2015-01-22 11:44  一个大菜B  阅读(945)  评论(0编辑  收藏  举报