由于需要使用c++对字符串进行切割
故对相关的知识做一个总结
1.使用
std::stringstream
切割字符串
比如:
std::stringstream str(text);
std::string tok;
while(getline(str,tok,(char)32)){}
2.还是使用std::stringstream流析出
比如:
std::stringstream str(s);
string t1,t2,t3,t4;
str >>t1;
str >>t2;
str >>t3;
str >>t4;
3.使用strtok
比如:
char* token = strtok(str.c_str()," ");
4.使用boost的
tokenizer
比如:
boost::tokenizer<> ss(s,char_separator(' '));
for(boost::tokenizer<>::iterator beg=ss.begin(); beg!=ss.end(); ++beg){cout<<*beg<<endl;}
不过其默认的分隔为空格和标点符号
如果需要定制其模板参数
可以按照下面的书写:
class char_separator
{
public:
char_separator(char c):sep(c){}
void reset(){}
template <typename InputIterator,typename Token>
bool operator()(InputIterator& next,InputIterator end,Token& tok)
{
tok = Token();
for(;next != end && *next == sep;++next);
if (next == end)
return false;
for(;next != end && *next != sep;++next)
{
tok += *next;
}
return true;
}
private:
char sep;
};
比如:
boost::tokenizer<char_separator> mytok(str,char_separator('@'));
for(boost::tokenizer<char_separator>::iterator beg=mytok.begin(); beg!=mytok.end(); ++beg)
{
if(index == 0)
text1 = *beg;
else if(index == 1)
text2 = *beg;
else if(index == 2)
text3 = *beg;
else if(index == 3)
text4 = *beg;
index++;
}
5.还是boost.
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <iostream>
#include <iterator>
#include <functional>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/find_iterator.hpp>
using namespace std;
using namespace boost;
int main(int argc, char *argv[])
{
vector<string> strlist;
string str("12 34 56 678 ccsdu2004");
split(strlist,str,is_any_of(" "),token_compress_on);
for(unsigned int index=0;index<strlist.size();index++)
{
cout<<index <<":"<<strlist[index]<<endl;
};
system("PAUSE");
return EXIT_SUCCESS;
}
6.其他不知道的方法若干
...