如何在C++中将数字字符串拆分为数组
How can I split string of numbers to array in C++?
我有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
相关文章:
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 字符串操作 - 字符计数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 在C++中使用 UTF-8 字符串和字符
- 如何使用SQLite将数据库中的值导出为C / C++中的字符串或字符?
- 递归形成字符串中所有数字字符的中间和?
- 如何在C++中为字符串添加字符?
- C++ 无法将 std::vector<BYTE> 转换为字符串或字符数组
- C++完全复制要字符串的字符列表,而不会忽略多个空格
- 我如何知道字符串中字符相对于英文字母的位置值?
- 如何将 VB.Net 字符串作为字符*传递给C++dll?
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 如何使用 c++ 将数字字符转换为字符串
- 使用find_if和isalnum在字符串中找到字母数字字符
- 在没有字符串或字符帮助的情况下查找数字的反面(例如:2500 reverse 0025)
- 确保字符串只包含字母数字字符的更好方法
- 在检测字符串是否包含数字字符时,这有什么问题
- 为什么我无法擦除字符串的数字字符?
- if语句-测试字符串或字符的大写,小写和数字
- 如何在 c++ 中从字符串中删除所有非字母数字字符