在不使用向量的情况下将字符串拆分为C ++中的数组 [英] splitting a string into an array in C++ without using vector

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

问题描述

我正在尝试使用C ++中的vector将用空格分隔的字符串插入到字符串 without 中.例如:

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

我希望输出为:

test
one
two
three.

我知道在C ++中还有其他问题要问字符串>数组,但是找不到满足我条件的答案:不使用向量将字符串拆分成数组.

I know there are already other questions asking string > array in C++, but I could not find any answer satisfying my conditions: splitting a string into an array WITHOUT using vector.

推荐答案

可以使用

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 <iostream>
#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天全站免登陆