這個方法中運用到了strtok函數:
原型:
char *strtok(char s[], const char *delim);
功能:
分解字符串爲一組字符串。s爲要分解的字符串,delim爲分隔符字符串。
例如:strtok("abc,def,ghi",","),最後可以分割成爲abc def ghi.尤其在點分十進制的IP中提取應用較多。
使用中的注意:
#include <stdio.h>
#include <string.h>#include <stdlib.h>
int strsplinum(char *str, const char*del) //判斷總共有多少個分隔符,目的是在main函數中構造相應的arr指針數組
{
char *first = NULL;
char *second = NULL;
int num = 0;
first = strstr(str,del);
while(first != NULL)
{
second = first+1;
num++;
first = strstr(second,del);
}
return num;
}
void split( char **arr, char *str, const char *del)//字符分割函數的簡單定義和實現
{
char *s =NULL;
s=strtok(str,del);
//printf("s:%s\n",s);
while(s != NULL)
{
//printf("s:%s\n",s);
*arr++ = s;
//printf("%s\n",*arr);
s = strtok(NULL,del);
}
}
int main(int argc,char *argv)
{
char *mm="2014-1-3-16-34-213";
char str[16] ;
strcpy(str,mm);
const char *del = "-"; //分隔符
int numTest = 1;
int i=0;
char *arr[6]; //利用指針數組對應分割好的字符串數組(即二維數組中的行數組)
numTest = strsplinum(str,del);
printf("the numbers of arry is : %d \n",numTest+1);
split(arr,str,del);
while(i<=numTest)
{
printf("%s\n",*(arr+(i++))); //打印分割好的字符串
}
return 0;
}
結果:
the numbers of arry is : 6
2014
1
3
16
34
213
請按任意鍵繼續. . .
方法二(C++方法):
#include <string.h>
#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
int main(int argc,char **argv)
{
//string test = "aa aa bbc cccd";
string test="2014-1-3-2";
vector<string> strvec;
string strtemp;
string::size_type pos1, pos2;
pos2 = test.find('-');
pos1 = 0;
while (string::npos != pos2)
{
strvec.push_back(test.substr(pos1, pos2 - pos1));
pos1 = pos2 + 1;
pos2 = test.find('-', pos1);
}
strvec.push_back(test.substr(pos1));
vector<string>::iterator iter1 = strvec.begin(), iter2 = strvec.end();
char *m;
while (iter1 != iter2)
{
cout << *iter1 << endl;
++iter1;
}
//cout<<m<<endl;
return 0;
}
結果:
2014
1
3
2
請按任意鍵繼續. . .