![](/img/trans.png)
[英]How to read the lines between two specific words in a text file (*.txt)?
[英]How to read text file between specific words?
我想要“个人资料名称”和“ ###”之间的文本。提取的文本应显示在文本浏览器中。 配置文件名称有所不同。 我的文本文件(harnish_data.txt)看起来像这样,
XYZ Profile
First Name :- XYZ
Second Name :- sssss
Last Name :- sssss
Favourite Food :- sssss
Favourite Actor :- sssss
Favourite Actress :- ssssss
###
PQR Profile
First Name :- PQR
Second Name :- hhhhh
Last Name :- hhhhh
Favourite Food :- hhhhhh
Favourite Actor :- hhhhhh
Favourite Actress :- hhhhh
###
现在,如果配置文件名称为XYZ,那么我希望XYZ配置文件之间的文本数据为###。 如果个人资料名称为PQR,则我希望PQR个人资料之间的文本为###。 配置文件的数量可能会增加。
我已经尝试过了,这里的detail_data.txt文件仅包含我的个人资料名称。
QFile file("detail_data.txt");
file.open(QIODevice::ReadWrite);
QTextStream inn(&file);
const QString contentt = inn.readLine(); //contentt contain profile name
qDebug() << contentt; // PQR
QFile MyFile("harnish_data.txt"); // contains profile data
MyFile.open(QIODevice::ReadWrite);
QTextStream in (&MyFile);
const QString content = in.readAll(); // contains profile data
QString srch (contentt + " " + "Profile");
qDebug() << srch << "search string"; // PQR Profile
int pos = content.indexOf(srch);
qDebug() << pos << "index of srch"; //155
if ( pos >= 0 )
{
QString restOfLine = content.mid(pos + srch.length(), srch.endsWith("###"));
qDebug() << srch.length() << "srch.length()"; //11
qDebug() << restOfLine << "restOfLine of mid"; //\nFirst Name :- PQR\nSecond Name :- hhhhh\nLast Name :- hhhhh\n\nFavourite Food :- hhhhhh\nFavourite Actor :- hhhhhh\nFavourite Actress :- hhhhh\n###\n\n" restOfLine of mid
}
ui->textBrowser->setText(in.readAll());
我已经运行了上面的代码,但是当我想要'profile name'和'###'之间的数据时,它为我提供了整个文本文件数据。
您的错误在以下行中:
ui->textBrowser->setText(in.readAll());
它应该是:
ui->textBrowser->setText(restOfLine);
首先搜索配置文件索引,然后搜索三个#:
QString srch(contentt + " " + "Profile");
int pos = content.indexOf(srch);
QString srch2("###");
int pos2 = content.indexOf(srch2);
if ( pos1 >= 0 && pos2 >= 0)
QString restOfLine = content.mid(pos1, pos2-pos1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.