strtok在分离有规律分隔符的字符串的时候,用处很方便,不过千万要记得_CRTIMP char * __cdecl strtok(char *, const char *)第一个参数不能指向存在于
静态存储空间的字符串,否则程序会崩溃异常。这个也是函数的不足之处。以下是简单实现
// StrTok.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<string.h>
#include<stdio.h>
#include<vector>
#include<iostream>
using namespace std;
int SplitString(char* SourcesStr,const char* seps,vector<char*> &strVec)
{
char* element;
int i=0;
if(strlen(SourcesStr)==0)
{
return -1;
}
if (strlen(seps)==0)
{
strVec.push_back(SourcesStr);
return 0;
}
cout << SourcesStr << endl;
cout << seps << endl;
element = strtok(SourcesStr, seps);
while (element != NULL)
{
strVec.push_back(element);
element = strtok( NULL, seps);
}
return 0;
}
int main(int argc, char* argv[])
{
vector<char*> vec;
char str[]="abc,bac,aaa,bbb"; //strtok不能指向静态区的字符串
int ret = SplitString(str,",",vec); //调用SplitString("abc,bac,aaa,bbb",",",vec);会发生异常
if (ret == -1)
{
return 0;
}
vector<char*>::iterator iter = vec.begin();
for (;iter != vec.end();++iter)
{
cout << *iter << endl;
}
return 0;
}