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

How can I split string of numbers to array in C++?

本文关键字:字符串 数字字符 拆分 数组 数字 C++      更新时间:2023-10-16

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

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

我用java做:

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

但是,如果没有外部库,我如何在C++中做到这一点。

用空格拆分字符串,对于每个标记(在您的例子中是数字(,将字符串转换为 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