c++ - 高效读取字符位置
问题描述
我有以下文本文件。每个数据字段由字符分隔|
,行分隔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';
解决方案
在伪代码中:
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.
推荐阅读
- cpu - 超线程与超标量执行
- java - 跨多个公共库共享单个类加载器是否安全
元素? - c++ - Omnet++ 如何在同一个工作区的不同项目中继承 cSimpleModule?
- python-3.x - 如何在 tkinter 中设置 Button 的限制,使其只执行一次?
- sql-server - 每天根据日期列将数据从 Prod 导出到较低环境
- swift - 实例方法要求 'NSObject' 符合
- python - 用于步进图的数据框中的 Python 重新排序级别
- c# - 插入问题
- php - 我已经在php中完成了自我加入,但它给出了错误的结果
- python - 如何通过odoo计算域搜索?