c++ - 在不使用 vector 的情况下将字符串拆分为 C++ 中的数组

标签 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.

我知道在 C++ 中已经有其他问题询问字符串 > 数组,但我找不到任何满足我的条件的答案:在不使用 vector 的情况下将字符串拆分为数组。

最佳答案

可以使用 std::stringstream 将字符串转换为流。类(它的构造函数接受一个字符串作为参数)。构建完成后,您可以在其上使用 >> 运算符(如常规基于文件的流),它将从中提取或 tokenize 单词:

#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++ - 在不使用 vector 的情况下将字符串拆分为 C++ 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16029324/

相关文章:

javascript - 如何从 Javascript 数组中完全删除元素

arrays - 如何清空整个数组?

c# - 在 C# 多行逐字字符串中转义 string.Format 的参数

C++构造函数继承

c++ - fprintf()/std::cout 不会将字符串的一部分打印到 stdout/stderr

php - 在 Twig 模板中设置多维数组中单个对象的值

python - 在 Python 中总结字符串列表

c++ - 使用 C 样式数组作为 STL 字符串操作的后端

c++ - 将线近似为平面图轮廓

c++ - Visual Studio 2010 - 排除文件类型