C++分割字符串

c++的標準庫string很多東西沒有提供,包括但不限於split/join/slice, 而用到的機會又很多, 雖然利用標準庫/第三方庫實現split功能的方式有千千萬, 本篇就按照how to split a string in c++中的幾種方式給出一下,已經能覆蓋到平時的使用場景了.

solution 1.1 : 字符流迭代器
使用場景:只有標準庫可用; 只對空格進行分割
原理:輸入流迭代器istream_iterator將輸入流(文件/string等)分割成若干元素, 分割是通過迭代器自增實現, 每自增一次迭代器就從輸入流中獲取一個元素直到末尾, 而尾迭代器不需要賦值, 默認就空的; 流迭代器分割輸入流的默認算法是按照空格來截取, 因此可以利用輸入流迭代器的此種特性來做字符串分割.
代碼:
std::istringstreamiss(text);std::istream_iteratorstd::string Itbegin =std::istream_iteratorstd::string(iss);std::istream_iteratorstd::string ItEnd =std::istream_iteratorstd::string();std::vectorstd::string results1(Itbegin, ItEnd);
solution 1.2 : 對輸入流重載>>
使用場景: 只有標準庫可用; 不僅僅只對空格進行分割
原理: 輸入流迭代器的自增實際上是調用了string的非成員函數operator>>, 在裏面給定了默認分割規則(按空格), 因此如果有其他需要, 可以繼承string類, 並重載非成員函數std::istream &operator>>(std::istream &is, std::string &ouput), 在函數實現中給定(或者用模板類制定)分割規則.
代碼:

classWordDelimitedByCommas :publicstd::string{ };std::istream &operator>>(std::istream &is, WordDelimitedByCommas &output) {returnstd::getline(is, output,’,’); } …std::stringtext2 =“Let,me,split,this,into,words”;std::istringstreamiss2(text2);autoItbegin2 =std::istream_iterator(iss2);autoItEnd2 =std::istream_iterator();std::vectorstd::string results2(Itbegin2, ItEnd2);
solution 2: boost::split
使用場景: 有boost可用; 分割規則客戶端指定
原理: client提供容器vector, boost分割之後存入其中
代碼:

std::vectorstd::string results3; boost::split(results3, text, boost::is_any_of(","));
solution 3: using ranges
使用場景: 可以使用其他第三方庫, head-only庫range-v3
原理:range-v3提供pipeline風格語法
代碼:

std::stringtext =“Let me split this into words”;autosplitText = text | view::split(’ ');
solution 4:
使用場景: 編譯器支持c++14; 待分割字符有一定規則(可以用正則表達式抽象)
原理: 正則表達式的迭代器std::regex_token_iterator按照正則因子的規則分割字符串A
代碼:

std::regexsep ("[ ,.]+");std::sregex_token_iteratortokens(text.cbegin(), text.cend(), sep, -1);std::sregex_token_iteratorend;std::cout<<"[solution:regex]"<<std::endl;for(; tokens !=end; ++tokens){std::cout<<“token found: “<< *tokens <<”\n”; }
總結
不需要自己利用標準庫提供的能力拼湊拼裝一個split的方式基本都在上面了.

如果一般的需求就用boost::split就很好了, 靈活且易用;

如果要求更高, 需要提取特定格式內的字符串, 那麼可以考慮regex方式;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章