【问题标题】:C++ to extract data between two stringsC ++提取两个字符串之间的数据
【发布时间】:2018-01-23 10:19:17
【问题描述】:

我正在寻找可以从两个字符串之间的文件 example.txt 中提取一些特定内容并忽略其余内容的 c++ 代码。例如文件 example.txt 有以下几行

xyz
abc
['Content','en']],
<html>hi this is a line <br></html>
',true], 
suzi 20

我想提取 ['Content','en']],',true], 之间的代码,这意味着

<html>hi this is a line <br></html>

请注意,我不是编程和使用 dev++ 编译器方面的专家

【问题讨论】:

  • 1.不要使用 dev-c++。 2.阅读regex
  • 正在为此寻找解决方案,可以在没有正则表达式的情况下完成吗?如果可以,请提供代码
  • @AhmedMehtab 所以不是代码编写服务;您应该发布您尝试过的内容并突出显示您遇到问题的具体问题。

标签: c++ extract fstream ifstream ofstream


【解决方案1】:

最简单的思路是将文件读入字符串,然后提取内容:

#include <string>
#include <sstream>

std::string extract(std::string const& tag_begin, std::string const& tag_end, std::istream& input)
{
    // file stream -> in memory string
    std::string filedata((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());

    // find content start and stop
    auto content_start = filedata.find(tag_begin);
    if (content_start == std::string::npos) {
        return ""; // error handling
    }
    content_start += tag_begin.size();
    auto content_end   = filedata.find(tag_end, content_start);
    auto content_size  = content_end - content_start;

    // extract (copy) content to other string
    auto content = filedata.substr(content_start, content_size);
    return content;
}

live demo

然后,您需要调整此通用解决方案以满足您的需求。

【讨论】:

  • 你可以直接从两个迭代器创建content字符串,不需要content_size
  • @bolov 我必须从 content_startcontent_stop 获取开始和结束迭代器,这同样很烦人。
  • 我认为content_startcontent_stop 是迭代器。我的错。
猜你喜欢
  • 1970-01-01
  • 2013-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 2020-10-15
  • 1970-01-01
  • 2019-10-25
相关资源
最近更新 更多