Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1555958
  • 博文数量: 290
  • 博客积分: 3468
  • 博客等级: 中校
  • 技术积分: 3461
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-28 22:21
文章分类

全部博文(290)

文章存档

2016年(13)

2015年(3)

2014年(42)

2013年(67)

2012年(90)

2011年(75)

分类: 嵌入式

2012-08-24 15:34:51


点击(此处)折叠或打开

  1. /* Copyright(C) 2012 for free
  2.  * All right reserved
  3.  */
  4. /**
  5.  * File split_string.c
  6.  * Brief 分割字符串
  7.  * Author sense, linuxboy2008@gmail.com
  8.  * Date 2012-08-24
  9.  */
  10. #include <string.h>
  11. #include <stdlib.h>
  12. #include <stdio.h>

  13. char *split(char *buf, char seprate, int num)
  14. {
  15.     char *tmp, *info;
  16.     int i = 0,n = 0,len = 0,times = 0;

  17.     tmp = buf;
  18. //    printf("buf :%s\n",buf);

  19.     for (i = 0; *buf != '\0';i++) {
  20.          n++;
  21.         if(*buf == seprate) {
  22.             len = n - 1;
  23.             n = 0;
  24.             if (times == (num -1) && times >= 0) {
  25.                 //buf++;
  26.                 tmp = buf + 1;
  27.             }
  28.             if (times == num) {
  29.                 if (!strncmp(tmp, buf,1)) {
  30.                     return NULL;
  31.                 }
  32.                 break;
  33.             }
  34.             times++;
  35.         }
  36.         buf++;
  37.     }
  38.     if (*buf == '\0'){ //此时len为上一节的长度
  39.         info = (char *)malloc((buf-tmp) + 1);
  40.         memset(info, 0, ((buf-tmp) + 1));
  41.         strcpy(info,tmp);
  42.     }
  43.     else {
  44.         info = (char *)malloc(len + 1);
  45.         memset(info, 0, (len + 1));
  46.         strncpy(info,tmp,len);
  47.     }
  48.     /*
  49.     info = (char *)malloc(len + 1);
  50.     for (i = 0;i < len;i++) {
  51.         info[i] = tmp[i];
  52.     }
  53.     info[i] = '\0';
  54.     */
  55. //    printf("info: %s\n",info);
  56.     tmp = NULL;

  57.     return info ;
  58. }

  59.  
  60. int main(int argc, char *argv[])
  61. {
  62.     char *buf = "2012|8|25";
  63.     char *buf1 = "2|||1|22|333|444||||||||2";
  64.     char *data = NULL;
  65.     int i = 0;
  66. #if 1
  67.     for (; i<3; i++)
  68.     {
  69.         data = split(buf, '|', i);
  70.         printf("%s\n",data);
  71.         free(data);
  72.         data = NULL;
  73.     }
  74. #endif
  75.     printf("buf: %s\n",buf1);
  76.     for (i=0; i<15; i++)
  77.     {
  78.         data = split(buf1, '|', i);
  79.         if (data != NULL) {
  80.             printf("i:%d %s\n",i,data);
  81.             free(data);
  82.             data = NULL;
  83.         }
  84.         else {
  85.             printf("i:%d, it's null .\n",i);
  86.         }
  87.     }

  88.     return 0;
  89. }
  90. #endif

测试:
$ gcc split_string.c  -o split
$ ./split
2012
8
25


阅读(1014) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~