贴一个分割字符串的类

来源:互联网 发布:淘宝群怎么添加到首页 编辑:程序博客网 时间:2024/04/28 16:24
template <class TString, class TVector>void Split(const TString &str,const TString &match,TVector &res,bool fullMatch = false){typedef TString::size_type (TString::*find_t)(const TString&, TString::size_type ) const;TString::size_type start = 0, skip = 1;find_t pfind = &TString::find_first_of;if ( fullMatch ){// use the whole match string as a key// instead of individual characters// skip might be 0. see search loop commentsskip = match.length();pfind = &TString::find;}while ( start != TString::npos ){// get a complete range [start..end)TString::size_type end = (str.*pfind)(match, start);// null strings always match in string::find, but// a skip of 0 causes infinite loops. pretend that// no tokens were found and extract the whole stringif (skip == 0) end = TString::npos;TString token = str.substr(start, end - start);// extract the token and add it to the result listres.push_back(token);// start the next rangeif ( (start = end) != TString::npos ) start += skip;}}
找到了一个贴代码的插件,很好很强大,贴一个很精巧的字符串分割函数
说明下,这个不是我原创的,是从网上找到的。我修改了下,加入泛型支持,TString可以是string/wstring;
TVector 可以是vector,list或者你自己的实现了push_back方法的类
原创粉丝点击