在 C++ 中解析字符串的最佳方法是什么
what is the best way to parse a string in c++
如何在 c++ 中最好地解析以下字符串:输入是一个字符串,例如:
(someString1 45)(someString2 2432)(anotherString 55) // .... etc.
当然,我们对字符串名称和值感兴趣。我们的目标是将字符串和值保存在映射中。有没有一种自动方法可以将字符串放在括号内?
谢谢
如果您的字符串不包含空格,一个简单的解决方案:
#include <iostream>
#include <string>
int main()
{
char c1, c2;
int n;
std::string s;
while (std::cin >> c1 >> s >> n >> c2 && c1 == '(' && c2 == ')')
{
std::cout << "Parse item: s = '" << s << "', number = " << n << "n";
}
}
此方法仅适用于正确的输入,无法中途恢复。如果需要,您可以使用getline
和)
作为分隔符来构建更复杂的东西。
下面就可以了:
string some; int n;
string s = "(someString1 45)(someString2 2432)(anotherString 55)";
stringstream sst(s); // to parse the string
while (sst.get() == '(' && sst >> some >> n && sst.get()==')') {
cout << some << "," << n << endl;
}
如果不存在左大括号,此循环将不会尝试读取某些字符串并n
。
如果您希望大括号之间的条目列表后面有内容,稍作更改甚至可以安全地解析进一步的输入字符串:
string s = "(someString1 45)(someString2 2432)(anotherString 55)thats the rest";
...
while (sst.get() == '(') { // open brace to process
if (sst >> some >> n && sst.get() == ')')
cout << some << "," << n << endl; // succesful parse of elements
else {
cout << "Wrong format !!n"; // something failed
if (!sst.fail()) sst.setf(ios::failbit); // case of missing closing brace
}
}
if (sst) { // if nothing failed, we are here because open brace was missing and there is still input
sst.unget(); // ready to parse the rest, including the char that was checked to be a brace
string rest;
getline(sst, rest);
cout << "The braces are followed by: " << rest << endl;
}
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 检测win32服务创建和删除的最佳方法
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将线程中的数据存储到全局容器的最佳方法?
- 将一系列整数放入类的最佳方法是什么?
- 在派生类中使用基类的私有成员变量的最佳方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 将 pybind11 绑定标记为已弃用的最佳方法
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++中变量混叠的最佳方法
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?