用C++从字符串中优雅地提取数据
Extracting data elegantly from a string in C++?
我可能有以下输入:
<Object::1 <1,2><3,4><3,3>>
<Object::2 <1,2><3,4>>
<Object::3 <1,2> 5>
我需要两个提取::之后的值(可能是字符串),然后在<>中提取后面的I个值。
因此,对于第一个例子,我想得到:
1<1,2><3,4><3,3>
我可以从字符串中读取,我只是不确定如何从中获得我想要的东西?
嗯,让我们首先将输入行读取为字符串。
std::string text_from_file;
getline(my_text_file, text_from_file);
你想跳过文本这涉及到使用std::string
的find
方法。
std::string::size_type position_in_string;
position_in_string = text_from_file.find("<Object::");
接下来,测试位置。毕竟,如果没有找到密钥字符串,我们就不想继续。
if (position_in_string != std::string::npos)
{
下一个棘手的部分是获取"::"后面的数字
这可以通过多种方式实现,我们将尝试std::istringstream
。我们需要从"::"之后的字符串中获取文本,该字符串被称为子字符串,缩写为substr
。
unsigned int quantity = 0;
std::istringstream string_input(text_from_file.substr(position_in_string));
我们可以在文本字符串上使用流提取运算符:
string_input >> quantity;
从输入文本中获取剩余的文本称为解析。与上述操作非常相似。你试试看。
StackOverflow中有许多帖子非常有用。通过搜索"[C++]解析从文件读取"来找到它们。
我认为这应该适用于(?<=::)([^<]+)s+.*?(<.*)>
演示
相关文章:
- JPG-如何从ICC配置文件部分APP2读取/提取数据
- 如何从多维向量中提取数据
- 从异构列表中提取数据
- 从 Windows 中的其他应用程序 GUI 中提取数据
- 如何从 qwebengineview qt5.9 中提取数据
- 如何从shared_ptr<T&>的引用中提取数据
- 从自定义结构数组中提取数据
- 无法从结构数组 C++ 中提取数据
- 用字符串::擦除在C 中提取数据
- C 从结构Deque提取数据
- 如何从 char[] 字符串中提取数据
- 用C++从字符串中优雅地提取数据
- 如何从用|分隔的txt文件中提取数据
- 如何从结构数组中提取数据
- 如何使用 C++11 <thread> 设计从源中提取数据的系统
- 从数据库中提取数据时使用QVariant的正确方法
- 提取数据范围的分隔符
- 从文本文件中查找和提取数据
- 是否有用于从HTML页面中提取数据的库
- 使用Boost::python从嵌入式python中提取数据