<分区>
我有 string s = "4 99 34 56 28";
我需要将这个字符串拆分为数组:[4, 99, 34, 56, 28]
我用java做的:
String line = reader.readLine();
String[] digits = line.split(" ");
但是我怎样才能用 C++ 实现呢?没有外部库。
<分区>
我有 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/