程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 用C實現字符串分割並返回所有子串,c實現字符串分割

用C實現字符串分割並返回所有子串,c實現字符串分割

編輯:關於C語言

用C實現字符串分割並返回所有子串,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;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved