C ++:将字符串分割为数组 [英] C++: splitting a string into an array

查看:1941
本文介绍了C ++:将字符串分割为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图插入用空格分隔成一个字符串数组字符串的没有的使用C ++向量。例如:

I am trying to insert a string separated by spaces into an array of strings without using vector in C++. For example:

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;
    }
}

我所要的输出是:

I want the output to be:

test
one
two
three.

我知道已经有很多要求的字符串>数组用C ++的问题。我意识到这可能是一个重复的问题,但我找不到我满足条件(将字符串分割阵列时不使用向量)任何回答。我在先进的道歉,如果这是一个重复的问题。

I know there are already a lot of questions asking string > array in C++. I realize this might be a duplicate question, but I could not find any answer satisfying my conditions (splitting a string into an array WITHOUT using vector). I apologize in advanced if this was a repeated question.

推荐答案

有可能使用的 的std :: stringstream的 类(它的构造函数以一个字符串作为参数)。一旦它的建成,可以使用&GT;&GT; 运营商就可以了(像普通文件基于流),这将提取或标记化的从中一句话:

It is possible to turn the string into a stream by using the std::stringstream class (its constructor takes a string as parameter). Once it's built, you can use the >> operator on it (like on regular file based streams), which will extract, or tokenize word from it:

#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;
    }
}

这篇关于C ++:将字符串分割为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆