我正在使用以下代码搜索文件并提供数据和关联的行号。但是在数十万行的情况下,这段代码是否足够快?我的电脑真的死机了几秒钟。我需要搜索一对整数并在逗号后返回其 RHS 值(一些统计数据),但使用以下代码我可以返回整行。
- 使用
split
函数解析返回的数据并获取我的 RHS 值是否是个好主意
或
- 根据 LHS 参数直接获取 RHS 值。 (好吧,我做不到)
任何人都可以帮助我实现上述两个中的任何一个吗?
这是我的代码:
#include <string>
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file( "index_hyper.txt" ) ;
std::string search_str = "401" ;
std::string line ;
int line_number = 0 ;
while( std::getline( file, line ) )
{
++line_number ;
if( line.find(search_str) != std::string::npos )
std::cout << "line " << line_number << ": " << line << '\n' ;
}
}
这是我的 index_hyper.txt
文件的内容:
18,22
20,37
151,61
200,62
156,63
158,64
159,65
153,66
156,67
152,68
154,69
155,56
156,14
157,13
160,122
161,1333
400,455
401,779
402,74
406,71
最佳答案
您可以使用以下代码完成上述代码的工作:
grep -n "^401," index_hyper.txt
如果你只想输出 RHS,你可以:
grep "^401," index_hyper.txt | sed "s/[^,]*,//"
如果您在没有 sed、grep、bash 等的 Windows 平台上,那么您可以通过安装 cygwin 轻松访问 unix 工具。 .
关于c++ - 使用 C++ 在文件中进行字符串搜索/索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19159006/