2012-02-10 50 views
1

我是C++的新手,我無法通過分隔符分割字符串,並將子字符串放入向量中。我如何將一個空字符串存儲到一個向量中

我的代碼如下:

vector<string> split(const string &s, const string &delim) 
{ 
    string::size_type pos = s.find_first_of(delim,0); 
    int start = 0; 
    vector<string> tokens; 

    while(start < s.size()) 
    { 
      if(start++ != pos + 1) 
        tokens.push_back(" "); 
      pos = s.find_first_of(delim, start); 
      tokens.push_back(s.substr(start, pos - start)); 
    } 

    for(vector<string>::size_type i = 0; i != tokens.size(); ++i) 
      cout << tokens[i]; 

    return tokens; 
} 

字符串和分隔符被傳遞到函數和並執行分割。這個函數假設將空字符串放入向量中,但不會爲我做。

例如,如果我調用該函數中主要爲:

int main() 
{ 
    split("<ab><>cd<", "<>"); 
} 

輸出假設是

"","ab","","","","cd","" 

減去報價

但輸出爲我的代碼目前是

ab b cd d 

任何幫助,將不勝感激。

+0

這裏有一些相關的問題,這可能有助於:http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c HTTP:/ /stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c http://stackoverflow.com/questions/4533652/how-to-split-string-using-istringstream-with- other-delimiter-than-whitespace http://stackoverflow.com/questio NS/5505965 /快字符串分割與 - 多定界符 – 2012-02-10 02:50:39

回答

1

這確實的伎倆...

#include <iostream> 
#include <vector> 

using namespace std; 

vector<string> split(string record, string token) { 
    vector<string> results; 
    size_t startPos = 0; 
    size_t pos = 0; 

    // Step: If either argument is empty then return 
    // an empty vector. 
    if (record.length() == 0 || token.length() == 0) { 
     return results; 
    } 

    // Step: Go through the record and split up the data. 
    while(startPos < record.length()) { 
     pos = record.find(token, startPos); 
     if (pos == string::npos) { 
      break; 
     } 

     results.push_back(record.substr(startPos, pos - startPos)); 
     startPos = pos + token.length(); 
    } 

    // Step: Get the last (or only bit). 
    results.push_back(record.substr(startPos, record.length() - startPos)); 

    // Step: Return the results of the split. 
    return results; 
} 

void printData(vector<string> list) { 
    for(vector<string>::iterator it = list.begin(); it < list.end(); it++) { 
     cout << *it << endl; 
    } 
} 

int main(int argc, char** argv) { 
    string record = ""; 
    string delim = ""; 

    if (argc == 3) { 
     record = argv[1]; 
     delim = argv[2]; 
     printData(split(record,delim)); 
    } else { 
     string record = "comma,delimited,data"; 
     string delim = ","; 
     printData(split(record,delim)); 

     record = "One<--->Two<--->Three<--->Four"; 
     delim = "<--->"; 
     printData(split(record,delim)); 
    } 
} 
0

看起來你的循環並沒有做出正確的事情:你在每次迭代中逐個字符地前進start。我會懷疑你真的想有一個當前位置,查找下一個分隔符,添加當前位置和分隔符的結果之間的字符串,使當前位置的字符分隔符後:

for (std::string::size_type start(0); start != s.npos;) 
{ 
    std::string::size_type end(s.find_first_of(delim, start)); 
    tokens.push_back(s.substr(start, end != s.npos? end - start: end)); 
    start = end != s.npos? end + 1: s.npos; 
} 
相關問題