Created
October 28, 2010 04:07
-
-
Save shihongzhi/650623 to your computer and use it in GitHub Desktop.
stringSplit的实现,以及foreach宏
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
using namespace std; | |
//无法使用typeof,因为这是gcc的扩展 | |
//#define foreach(container,it) for(typeof((container).begin()) it=(container).begin();it!=(container).end();++it) | |
#define foreach(type,container,it) for(type::iterator it=(container).begin();it!=(container).end();++it) | |
void SplitString(const string &srcStr,const string &splitStr,vector<string> &destVec) | |
{ | |
int newPos,oldPos; | |
newPos=oldPos=0; | |
string tempData; | |
while(1) | |
{ | |
newPos=srcStr.find(splitStr,oldPos); | |
if(newPos!=string::npos) | |
{ | |
tempData=srcStr.substr(oldPos,newPos-oldPos); | |
destVec.push_back(tempData); | |
oldPos=newPos+splitStr.size(); | |
} | |
else if(oldPos<=srcStr.size()) | |
{ | |
tempData=srcStr.substr(oldPos); | |
destVec.push_back(tempData); | |
break; | |
} | |
else | |
{ | |
break; | |
} | |
} | |
} | |
int main(int argc,char* argv[]) | |
{ | |
string src=",,w,,ai,,,nio,,"; | |
string splitStr=",,"; | |
vector<string> destVec; | |
SplitString(src,splitStr,destVec); | |
//for(vector<string>::iterator it=destVec.begin();it!=destVec.end();it++) | |
foreach(vector<string>,destVec,it) | |
cout<<*it<<endl; | |
getchar(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment