C ++:将字符串拆分为数组

时间:2013-04-16 05:19:52

标签: c++ arrays string vector

我试图在C ++中使用vector将一个用空格分隔的字符串插入一个字符串数组而不用。例如:

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.

我知道有很多问题要求字符串&gt; C ++中的数组。我意识到这可能是一个重复的问题,但我找不到任何满足我条件的答案(将字符串拆分为数组而不使用向量)。如果这是一个重复的问题,我会提前道歉。

6 个答案:

答案 0 :(得分:37)

可以使用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;
    }
}

答案 1 :(得分: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;
}

答案 2 :(得分: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;
}

答案 3 :(得分: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

答案 4 :(得分:0)

这是一个建议:在字符串中使用两个索引,比如startendstart指向要提取的下一个字符串的第一个字符,end指向属于要提取的下一个字符串的最后一个字符后的字符。 start从零开始,end获取start之后的第一个字符的位置。然后在[start..end)之间取一个字符串并将其添加到数组中。你一直走到字符串的末尾。

答案 5 :(得分:0)

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

int main() {

    string s1="split on     whitespace";
    istringstream iss(s1);
    vector<string> result;
    for(string s;iss>>s;)
        result.push_back(s);
    int n=result.size();
    for(int i=0;i<n;i++)
        cout<<result[i]<<endl;
    return 0;
}

输出:-

分割

空格

相关问题