实现c++的string的split效能
今天写程序,遇到了一个要实现string.split()这个的一个函数。python里面有,qt里面有,c++里面没有。照着网上抄了一个,放在这里。有需要的时候直接拽过去用,否则老是写了小例子就扔,用的时候没有,也是个麻烦事
例如 “aa*bb*cc” 会存储成vector<string> "aa" "bb" "cc"
// temp1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char a[] = "abc*123*xyz"; //目标是解析成 abc 123 xyz 然后存储在下面的变量 vector<string>中
string strArry = a;
vector<string> strArryList;
size_t last = 0;
size_t index = strArry.find_first_of("*",last); //找到last坐标后面的第一个*
while( index != std::string::npos )//找到一个推进vector一个,一直到找到了最后
{
strArryList.push_back( strArry.substr(last, index-last));
last = index +1;
index = strArry.find_first_of("*",last);
}
if(index - last > 0) //记得把最后一个推进去.这里是"xyz"
{
strArryList.push_back( strArry.substr(last, index-last));
}
for(int i = 0; i < strArryList.size(); i++)
std::cout<<strArryList[i]<<std::endl;
getchar();
return 0;
}