gpt4 book ai didi

C++ 从一个大文件中解析一行

转载 作者:行者123 更新时间:2023-11-28 08:31:33 25 4
gpt4 key购买 nike

我已经从内存映射文件 Win API 中将整个文件读入字符串

CreateFile( "WarandPeace.txt", GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 )

等...

每一行都以 CRLF 结束。我需要在“I love Spam and Eggs”行中找到类似“Spam”的行(并以字符串(或指向字符串中位置的指针)返回整行(不带 CRLF) 原始字符串无法更改。

已编辑:

像这样:

string ParseStr( string sIn, string sDelim, int nField )
{
int match, LenStr, LenDelim, ePos, sPos(0), count(0);
string sRet;

LenDelim = sDelim.length();
LenStr = sIn.length();
if( LenStr < 1 || LenDelim < 1 ) return ""; // Empty String
if( nField < 1 ) return "";
//=========== cout << "LenDelim=" << LenDelim << ", sIn.length=" << sIn.length() << endl;


for( ePos=0; ePos < LenStr; ePos++ ) // iterate through the string
{ // cout << "sPos=" << sPos << ", LenStr=" << LenStr << ", ePos=" << ePos << ", sIn[ePos]=" << sIn[ePos] << endl;
match = 1; // default = match found
for( int k=0; k < LenDelim; k++ ) // Byte value
{
if( ePos+k > LenStr ) // end of the string
break;
else if( sIn[ePos+k] != sDelim[k] ){ // match failed
match = 0; break; }
}
//===========

if( match || (ePos == LenStr-1) ) // process line
{
if( !match ) ePos = LenStr + LenDelim; // (ePos == LenStr-1)
count++; // cout << "sPos=" << sPos << ", ePos=" << ePos << " >" << sIn.substr(sPos, ePos-sPos) << endl;
if( count == nField ){ sRet = sIn.substr(sPos, ePos-sPos); break; }
ePos = ePos+LenDelim-1; // jump over Delim
sPos = ePos+1; // Begin after Delim
} // cout << "Final ePos=" << ePos << ", count=" << count << ", LenStr=" << LenStr << endl;
}// next

return sRet;
}

如果喜欢,请投上一票。如果没有,让我们看看你得到了什么。

最佳答案

如果您尝试匹配更复杂的模式,那么您总是可以回退到 boost 的正则表达式库。

参见:http://www.boost.org/doc/libs/1_41_0/libs/regex/doc/html/index.html

#include <iostream>
#include <string>
#include <boost/regex.hpp>

using namespace std;

int main( )
{
std::string s;
std::string sre("Spam");
boost::regex re;

ifstream in("main.cpp");
if (!in.is_open()) return 1;

string line;
while (getline(in,line))
{
try
{
// Set up the regular expression for case-insensitivity
re.assign(sre, boost::regex_constants::icase);
}
catch (boost::regex_error& e)
{
cout << sre << " is not a valid regular expression: \""
<< e.what() << "\"" << endl;
continue;
}
if (boost::regex_match(line, re))
{
cout << re << " matches " << line << endl;
}
}
}

关于C++ 从一个大文件中解析一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1786294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com