用C++从字符串中优雅地提取数据

Extracting data elegantly from a string in C++?

本文关键字:提取 数据 C++ 字符串      更新时间:2023-10-16

我可能有以下输入:

  <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::stringfind方法。

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+.*?(<.*)>演示