2013-04-16 34 views
16

我試圖插入下,使用矢量++由空格分隔成字符串的陣列而不的字符串。例如:C++:將字符串分割爲一個數組

using namespace std; 
int main() { 
    string line = "test one two three."; 
    string arr[4]; 

    //codes here to put each word in string line into string array arr 
    for(int i = 0; i < 4; i++) { 
     cout << arr[i] << endl; 
    } 
} 

我所要的輸出是:

test 
one 
two 
three. 

我知道已經有很多要求的字符串>數組用C++的問題。我意識到這可能是一個重複的問題,但我找不到滿足我的條件的任何答案(將字符串拆分爲數組而不使用向量)。如果這是一個重複的問題,我很抱歉。

+0

你會如何開始在單獨的行上打印每個單詞? –

+0

使用substr並找到 – 999k

+1

或'strtok'。 。 –

回答

31

有可能通過使用std::stringstream類轉串入一個流(它的構造採用字符串作爲參數)。一旦它的建成,您可以使用它的>>運營商(像常規的基於文件流),這將提取,或記號化從中字:

#include <sstream> 

using namespace std; 

int main(){ 
    string line = "test one two three."; 
    string arr[4]; 
    int i = 0; 
    stringstream ssin(line); 
    while (ssin.good() && i < 4){ 
     ssin >> arr[i]; 
     ++i; 
    } 
    for(i = 0; i < 4; i++){ 
     cout << arr[i] << endl; 
    } 
} 
+2

這個答案非常簡單,重點突出,更重要的是作品!非常感謝你! – txp111030

+0

不客氣! – didierc

+0

它爲我分裂個別角色。 – Krii

0

這是一個建議:在字符串中使用兩個索引,如startendstart指向要提取的下一個字符串的第一個字符,end指向最後一個屬於要提取的下一個字符串後的字符。 start從零開始,end獲得start後的第一個字符的位置。然後你把[start..end)之間的字符串加到你的數組中。你繼續前進,直到你擊中字符串的末尾。

2
#define MAXSPACE 25 

string line = "test one two three."; 
string arr[MAXSPACE]; 
string search = " "; 
int spacePos; 
int currPos = 0; 
int k = 0; 
int prevPos = 0; 

do 
{ 

    spacePos = line.find(search,currPos); 

    if(spacePos >= 0) 
    { 

     currPos = spacePos; 
     arr[k] = line.substr(prevPos, currPos - prevPos); 
     currPos++; 
     prevPos = currPos; 
     k++; 
    } 


}while(spacePos >= 0); 

arr[k] = line.substr(prevPos,line.length()); 

for(int i = 0; i < k; i++) 
{ 
    cout << arr[i] << endl; 
} 
+0

如果string :: npos沒有找到被搜索的字符串而不是0,那麼'string :: find'返回'string :: npos'。 – RedX

+0

std :: string :: npos是一個靜態成員常數值,其值爲鍵入size_t。此常量的值爲-1,這是因爲size_t是無符號整型,它是此類型最大的可表示值。 –

2
#include <iostream> 
#include <sstream> 
#include <iterator> 
#include <string> 

using namespace std; 

template <size_t N> 
void splitString(string (&arr)[N], string str) 
{ 
    int n = 0; 
    istringstream iss(str); 
    for (auto it = istream_iterator<string>(iss); it != istream_iterator<string>() && n < N; ++it, ++n) 
     arr[n] = *it; 
} 

int main() 
{ 
    string line = "test one two three."; 
    string arr[4]; 

    splitString(arr, line); 

    for (int i = 0; i < 4; i++) 
     cout << arr[i] << endl; 
} 
1

簡單:

const vector<string> explode(const string& s, const char& c) 
{ 
    string buff{""}; 
    vector<string> v; 

    for(auto n:s) 
    { 
     if(n != c) buff+=n; else 
     if(n == c && buff != "") { v.push_back(buff); buff = ""; } 
    } 
    if(buff != "") v.push_back(buff); 

    return v; 
} 

Follow link