您的位置:首页 > 编程语言 > C语言/C++

C语言中的字符串中的分隔---split

2014-01-03 21:55 330 查看
这个方法中运用到了strtok函数:

原型:

char *strtok(char s[], const char *delim);

功能:

分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。

例如:strtok("abc,def,ghi",","),最后可以分割成为abc def ghi.尤其在点分十进制的IP中提取应用较多。

使用中的注意:

strtok函数会破坏被分解字符串的完整,调用前和调用后的s已经不一样了。如果

要保持原字符串的完整,可以使用strchr和sscanf的组合等

#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

请按任意键继续. . .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: