2012-05-27 65 views
0

可能重複:
How to split a string in C++?最簡單的方法來拆分字符串並插入向量?

什麼是分裂基於特定字符的字符串,然後將元素插入載體的最簡單的方法?

請不要建議boost.algorithm.split

+0

這裏有這個問題很多重複。更近的一個在這裏:http://stackoverflow.com/questions/5607589/right-way-to-split-an-stdstring-into-a-vectorstring,但你可能會發現在FAQ中很好的東西:http:// stackoverflow.com/questions/236129/how-to-split-a-string-in-c – chris

+2

@ user997112:請描述你正在尋找什麼答案,而不是你正在尋找的答案。告訴我們不要建議boost :: algorithm不是很有建設性,因爲它不告訴我們是否可以推薦另一個第三方庫。或者如果我們可以從標準庫建議功能。如果你的意思是「我不能使用Boost的任何部分,那麼解決方案就不能依賴那個特定的庫」,這麼說。如果你的意思是「我不能使用任何第三方庫,那麼答案只能依賴於C++標準庫」。 – jalf

+2

如果你的意思是「我根本無法使用圖書館解決方案,答案必須從頭開始寫」,這樣說。簡而言之,告訴我們有效答案必須滿足的約束條件。簡單地指出*個人*無效的答案並不能真正幫助我們回答這個問題 – jalf

回答

1

有很多方法解析字符串,這裏是一個使用SUBSTR()

#include <iostream> 
#include <vector> 
#include <string> 
using namespace std; 

int main() 
{ 
    string strLine("Humpty Dumpty sat on the wall"); 
    string strTempString; 
    vector<int> splitIndices; 
    vector<string> splitLine; 
    int nCharIndex = 0; 
    int nLineSize = strLine.size(); 

    // find indices 
    for(int i = 0; i < nLineSize; i++) 
    { 
     if(strLine[i] == ' ') 
      splitIndices.push_back(i); 
    } 
    splitIndices.push_back(nLineSize); // end index 

    // fill split lines 
    for(int i = 0; i < (int)splitIndices.size(); i++) 
    { 
     strTempString = strLine.substr(nCharIndex, (splitIndices[i] - nCharIndex)); 
     splitLine.push_back(strTempString); 
     cout << strTempString << endl; 
     nCharIndex = splitIndices[i] + 1; 
    } 

    getchar(); 

    return 0; 
}