首页 > 解决方案 > 高效读取字符位置

问题描述

我有以下文本文件。每个数据字段由字符分隔|,行分隔newline

|1|data1|data2|....|....|....|\n
|2|data2|data3|....|....|....|\n
.
.

我想收集第二个和第三个|符号之间的数据字段。我的计划是找到第二个|符号的位置并读取数据直到第三个 | 然后找到新的行符号重复相同的。我听说如果我们有位置,我们可以使用 lseek 函数移动光标光标。我可以逐个字符地阅读,直到找到第二个和第三个|符号,但是我想使用更快的方法来查找新的行符号。最有效的方法是什么?以下是我的源代码

  std::string str ("1|data1|data2|....|....|....|\n");
  std::string str2 ("|");
  std::size_t firstpipe = str.find(str2);
  std::size_t secondpipe = str.find(str2,secondpipe+1);
  if (found!=std::string::npos)
       std::cout << "first '|' found at: " << firstpipe << '\n';
       std::cout << "scond '|' found at: " << secondpine << '\n';

标签: c++

解决方案


在伪代码中:

while( read line with `std::getline` into `std::string`)
    find first separator with `std::string::find`
    if not found skip line
    find second separator with `std::string::find` starting from first separator + 1
    if not found skip line
    find third separator with `std::string::find` starting from second separator position + 1
    use `std::string::substr(secondPos+1,thirdPos-secondPos-1)` to get your datablock.

推荐阅读