2014-04-02 172 views
3

假設我有串狀分割字符串分隔符

Harry potter was written by J. K. Rowling 

如何使用wasby作爲分隔符分割字符串,並獲得導致C++載體?

我知道分裂使用多個字符,但不使用多個字符串。

+0

怎麼樣的正則表達式記號迭代?:http://en.cppreference.com/w/cpp/正則表達式/ regex_token_iterator – tgmath

+0

我想盡可能不使用正則表達式,直到它可能,但正則表達式的答案,如果可能的給出的例子也將是有益的。 – psyche

回答

3

如果使用C++ 11和鏗鏘有使用正則表達式字符串標記的解決方案:

#include <fstream> 
#include <iostream> 
#include <algorithm> 
#include <iterator> 
#include <regex> 

int main() 
{ 
    std::string text = " Harry potter was written by J. K. Rowling."; 

    std::regex ws_re("(was)|(by)"); 
    std::copy(std::sregex_token_iterator(text.begin(), text.end(), ws_re, -1), 
       std::sregex_token_iterator(), 
       std::ostream_iterator<std::string>(std::cout, "\n")); 


} 

輸出是:

Harry potter 
written 
J. K. Rowling. 

可悲的是gcc4.8沒有正則表達式完全集成。但鏗鏘編譯並正確鏈接。

+0

對不起,沒有C++ 11現在,使用gcc – psyche

+0

如果你可以給示例使用boost,那麼BOOST也是有用的,那麼它也會有幫助。 – psyche

1

暴力方法,而不是推動,沒有C++ 11,優化多人歡迎:

/** Split the string s by the delimiters, place the result in the 
    outgoing vector result */ 
void split(const std::string& s, const std::vector<std::string>& delims, 
      std::vector<std::string>& result) 
{ 
    // split the string into words 
    std::stringstream ss(s); 
    std::istream_iterator<std::string> begin(ss); 
    std::istream_iterator<std::string> end; 
    std::vector<std::string> splits(begin, end); 

    // then append the words together, except if they are delimiter 
    std::string current; 
    for(int i=0; i<splits.size(); i++) 
    { 
     if(std::find(delims.begin(), delims.end(), splits[i]) != delims.end()) 
     { 
      result.push_back(current); 
      current = ""; 
     } 
     else 
     { 
      current += splits[i] + " " ; 
     } 
    } 

    result.push_back(current.substr(0, current.size() - 1)); 
} 
+0

令牌結尾和開始處產生的空白不正確。例如。例如,我得到'哈利波特','寫','J。 K.羅琳'而不是'哈利波特','書面','J. K.羅琳'。 – tgmath

+0

@tgmath謝謝,修正! – fritzone