2013-04-16 35 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