Chinaunix首页 | 论坛 | 博客
  • 博客访问: 60411
  • 博文数量: 34
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 267
  • 用 户 组: 普通用户
  • 注册时间: 2013-05-29 13:17
文章分类

全部博文(34)

文章存档

2014年(1)

2013年(33)

我的朋友

分类: C/C++

2013-09-04 22:43:57

"361/310/2071 362/311/2072 363/312/2073"
按空格和'/'分割字符串保存到数组中
方法一:使用char 二维数组,初始化数组大小
  1. char strTemp[8][50];

  2. void StrSplit(char* str,int n)
  3. {
  4.     int iRow=0,iColumn=0;
  5.     for (int i=0;i<n;i++,str++)
  6.     {
  7.         if (*str!=' ' && *str!='/')
  8.         {
  9.             strTemp[iRow][iColumn]=*str;
  10.             iColumn++;
  11.         }
  12.         else
  13.         {
  14.             strTemp[iRow][iColumn]='\0';
  15.             iColumn=0;
  16.             iRow++;
  17.         }
  18.     }
  19.     strTemp[iRow][iColumn]='\0';
  20. }




  21. char str[]="361/310/2071 362/311/2072 363/312/2073";
  22.     printf("%s\n",str);
  23.     StrSplit(str,strlen(str));
  24.     for (int i=0;i<9;i++)
  25.     {
  26.         printf("%s\n",strTemp[i]);
  27.     }
方法二:使用string一维数组

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. string* split(string a,char ch,int& num)
  5. {
  6.     int chCount=count(a.begin(), a.end(), ch);
  7.     string *b=new string[chCount + 1];
  8.     int j=0;
  9.     for (int i=0; i<chCount; i++)
  10.     {
  11.         for (;j<a.length(); j++)
  12.         {
  13.             if(a[j] != ch && a[j]!=' ')
  14.             {
  15.                 b[i]+=a[j];
  16.             }
  17.             else
  18.             {
  19.                 j++;
  20.                 break;
  21.             }
  22.         }
  23.     }
  24.     num=chCount+1;
  25.     return b;
  26. }
  27. int main()
  28. {
  29.     string a="361/310/2071 362/311/2072 363/312/2073";
  30.     string *str;
  31.     int num=0;
  32.     str=split(a, '/', num);
  33.     for(int i=0;i<num;i++)
  34.     {
  35.         cout<<*str<<endl;
  36.         str++;
  37.     }
  38.     return 0;
  39. }
阅读(1729) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~