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 comments skip = 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 string if (skip == 0) end = TString::npos; TString token = str.substr(start, end - start); // extract the token and add it to the result list res.push_back(token); // start the next range if ( (start = end) != TString::npos ) start += skip; } }
找到了一个贴代码的插件,很好很强大,贴一个很精巧的字符串分割函数
说明下,这个不是我原创的,是从网上找到的。我修改了下,加入泛型支持,TString可以是string/wstring;
TVector 可以是vector,list或者你自己的实现了push_back方法的类