2014-02-18 44 views
3

我有一個這樣的字符串:如何分割字符串並使用boost :: split保持分隔符?

std::string input("I #am going to# learn how #to use #boost# library#"); 

我這樣做:

std::vector<std::string> splitVector; 
boost::split(splitVector, input, boost::is_any_of("#")); 

,並得到這樣的:(splitVector)

splitVector: 
     "I " 
     "am going to" 
     " learn how " 
     "to use " 
     "boos" 
     " library" 
     "" // **That's odd, why do I have an empty string here ?** 

但需要的東西是這樣的:

splitVector: 
    "I " 
    "#am going to" 
    "# learn how " 
    "#to use " 
    "#boost" 
    "# library" 
    "#" 

如何做到這一點?或者,也許有另一種方法來在推動庫中做到這一點? 爲什麼我會在splitVector中得到空字符串?

+0

爲什麼你需要保持分隔符? – kaspersky

+0

@ gg.kaspersky,好問題!結果我必須恢復相同的字符串(使用splitVector來構建它),並且我有一個問題來檢測字符串中有多少個分隔符,即奇數或偶數,換句話說,我總是將其恢復,因爲它有偶數個分隔符。例如:如果我有字符串「#test」和「#test#」並分割它,請獲取第一個字符串「test」,並將相同的第二個字符串「test」,並將這兩個字符串還原爲「#test#」 –

+0

由於最後一個分隔符後面的輸入字符串爲空,因此存在空字符串。由於您的分隔符是單個字符,因此您可以簡單地將該字符前綴(或附加)爲結果字符串。如果有很多不同的分隔符,我不認爲增強分割有你需要的功能。請參閱例如[this](http://stackoverflow.com/questions/1511029/tokenize-a-string-and-include-delimiters-in-c)其他解決方案的問題。 – user2079303

回答

5

不能使用boost::split,因爲使用來自boost/algorithm/string/find_iterator.hppsplit_iterator的內部實現吞下了令牌。

但是你可以用boost::tokenizer獲得通過,因爲它有一個選項,以保持分隔符:

每當一個分隔符輸入序列看出,目前令牌結束,一個新的令牌開始。 dropped_delims中的分隔符不會顯示爲輸出中的標記,而retain_delims中的分隔符會顯示爲標記。
http://www.boost.org/doc/libs/1_55_0/libs/tokenizer/char_separator.htm

See next live:

#include <iostream> 
#include <string> 
#include <boost/tokenizer.hpp> 

int main() { 
    // added consecutive tokens for illustration 
    std::string text = "I #am going to# learn how ####to use #boost# library#";  
    boost::char_separator<char> sep("", "#"); // specify only the kept separators 
    boost::tokenizer<boost::char_separator<char>> tokens(text, sep); 
    for (std::string t : tokens) { std::cout << "[" << t << "]" << std::endl; } 
} 
/* Output: 
[I ] 
[#] 
[am going to] 
[#] 
[ learn how ] 
[#] 
[#] 
[#] 
[#] 
[to use ] 
[#] 
[boost] 
[#] 
[ library] 
[#] */