c++ - 如何在 C++ 中将数字字符串拆分为数组?

标签 c++ arrays string

<分区>

我有 string s = "4 99 34 56 28";

我需要将这个字符串拆分为数组:[4, 99, 34, 56, 28]

我用java做的:

String line = reader.readLine();
String[] digits = line.split(" ");

但是我怎样才能用 C++ 实现呢?没有外部库。

最佳答案

Split the string by spaces ,并且对于每个标记(在您的情况下为数字),将字符串转换为 int,如下所示:

#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <string> // stoi

using namespace std;

int main(void)
{
    string s("4 99 34 56 28");
    string buf;      
    stringstream ss(s); 

    vector<int> tokens;

    while (ss >> buf)
        tokens.push_back(stoi(buf));

    for(unsigned int i = 0; i < tokens.size(); ++i)
      cout << tokens[i] << endl;

    return 0;
}

输出:

4
99
34
56
28

关于c++ - 如何在 C++ 中将数字字符串拆分为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56480159/

相关文章:

c - 获取数组元素的地址

html - 如何允许在传递给 HTML 值属性的字符串中使用双引号和单引号?

c++ - 在 C++ 中反转字符串

c++ - 指针访问冲突? - C++

c++ - 将 ASCII 字符串转换为十进制和十六进制表示形式

C++ 恢复流 fmtflags

javascript - 如何在表单提交时添加嵌套对象?

php - highchart mysql json问题

c - 是否可以在不知道c中数组长度的情况下使用gets?

c++ - 在 C++ 中,我是否需要在关闭程序之前释放内存