2012-03-22 39 views
4

我有下列形式 a = x + yabc = xyz + 56 + 5f(p)串標記化++包括定界符

我需要的是來標記串,使得我讀取每個operatoroperand 所以對於a = x + y令牌返回的串應該是a,=,x,+,y,如果是abc=xyz+5則應該返回abc,=,xyz,+,5。請注意,有可能會或可能不會是空間operatoroperands

之間,這是我曾嘗試

void tokenize(std::vector<std::string>& tokens, const char* input, const char* delimiters) { 
    const char* s = input; 
    const char* e = s; 
    while (*e != 0) { 
     e = s; 
     while (*e != 0 && strchr(delimiters, *e) == 0) { 
      ++e; 
     } 
     if (*e != ' ' && strchr(delimiters, *e) != 0){ 
      std::string op = ""; 
      op += *e; 
      tokens.push_back(op); 
     } 
     if (e - s > 0) { 
      tokens.push_back(std::string(s,e - s)); 
     } 
     s = e + 1; 
    } 
} 
+3

這似乎是功課 – CAbbott 2012-03-22 13:30:18

+1

如果沒有家庭作業,我希望看到一個[Boost.Spirit(HTTP:// WWW .boost.org/doc/libs/1_49_0/libs/spirit/doc/html/index.html)回答。我從來沒有完全明白如何使用它。 – 2012-03-22 13:32:34

+0

找到了答案? – Michael 2012-06-09 22:30:24

回答

5

您可以使用此實現。 第一個參數是要標記的std :: string,第二個參數是要使用的分隔符。它返回一個字符串的標記化向量。非常簡單而高效。

vector<string> tokenizeString(const string& str, const string& delimiters) 
{ 
    vector<string> tokens; 
    // Skip delimiters at beginning. 
    string::size_type lastPos = str.find_first_not_of(delimiters, 0); 
    // Find first "non-delimiter". 
    string::size_type pos = str.find_first_of(delimiters, lastPos); 

    while (string::npos != pos || string::npos != lastPos) 
    { // Found a token, add it to the vector. 
     tokens.push_back(str.substr(lastPos, pos - lastPos)); 
     // Skip delimiters. Note the "not_of" 
     lastPos = str.find_first_not_of(delimiters, pos); 
     // Find next "non-delimiter" 
     pos = str.find_first_of(delimiters, lastPos); 
    } 
    return tokens; 
} 
+0

這一個將刪除分隔符,它不會推送在字符串中發現的分隔符 – Avinash 2012-03-22 13:36:19

+0

@Avinash這是標記化的要點。 – manasij7479 2012-03-22 14:00:50

+0

@ manasij7479修復了這個問題 – Avinash 2012-03-22 14:04:06

4

此示例使用boost tokenizer以實現期望的行爲:

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

using namespace std; 
using namespace boost; 

int main(int , char* []) 
{ 
    const string formula = " ABC + BYZ =6 +5"; 

    typedef boost::tokenizer<boost::char_separator<char> > tokenizer; 
    boost::char_separator<char> sep(" ", "+-="); 

    tokenizer tokens(formula, sep); 

    for (tokenizer::iterator tok_iter = tokens.begin();tok_iter != tokens.end(); ++tok_iter) 
     std::cout << "<" << *tok_iter << "> "; 

    return 0; 
} 

輸出

<ABC> < + > <BYZ> <=> <個+ >

空間被跳過,分隔符包括

+0

謝謝,但我正在尋找非增強解決方案 – Avinash 2012-03-22 14:04:25