gpt4 book ai didi

c++ - 如何使用 Qt 库从文本文件中获取字符串

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

我想从文本文件中获取一些字符串。我知道如何获取文本文件的整个字符串

QTextStream Stream (GEO); 
QString text;
do
{
text = Stream.readLine();

}
while(!text.isNull());

获取 QString 文本下的所有文本效果很好,但我只需要文本中的一些特定字符串,示意性地如下:

if the text "start" appears in the Qstring text (or the QTextStream Stream) 

save the following text under QString First

until the text "end" appears

谁能告诉我该怎么做,甚至可以给我一个小例子吗?

最佳答案

您可以使用的一件事是使用 indexOf() 获取“开始”和“结束”的索引,然后使用:

QString x = "start some text here end";
QString s = "start";
QString e = "end"
int start = x.indexOf(s, 0, Qt::CaseInsensitive); // returns the first encounter of the string
int end = x.indexOf(e, Qt::CaseInsensitive); // returns 21

if(start != -1) // we found it
QString y = x.mid(start + s.length(), end);

或 midRef 如果您不想创建新列表。您可能还必须处理“结束”,否则您可能会从 0 到 -1,这不会返回任何内容。也许(结束>开始?结束:开始)

编辑:没关系。如果 end == -1 就意味着它将返回所有内容直到结束(默认情况下第二个参数是 -1)。如果您不想要这个,您可以改用我的示例,并在选择“结束”时使用某种 if 语句

编辑:注意到我读错了文档,这将定义。工作:

#include <QDebug>

int main(int argc, char *argv[]) {
QString x = "start some text here end";
QString s = "start";
QString e = "end";
int start = x.indexOf(s, 0, Qt::CaseInsensitive);
int end = x.indexOf(e, Qt::CaseInsensitive);

if(start != -1){ // we found it
QString y = x.mid(start + s.length(), ((end - (start + s.length())) > -1 ? (end - (start + s.length())) : -1)); // if you dont wanna pass in a number less than -1
or
QString y = x.mid(start + s.length(), (end - (start + s.length()))); // should not be any issues passing in a number less than -1, still works

qDebug() << y << (start + s.length()) << (end - (start + s.length()));
}
}

这会产生以下结果。最后两个数字是“开始”结束和“结束”开始的地方。

x = "start some text here end" => " some text here " 5 16

x = " some text here end" => no outprint

x = "testing start start some text here end" => " start some text here " 13 22

x = "testing start start some text here" => " start some text here" 13 -14

或者您可以使用正则表达式来完成。在这里为您写了一个非常简单的片段:

#include <QDebug>
#include <QRegExp>

int main(int argc, char *argv[]) {
QRegExp rxlen("(start)(.*(?=$|end))");
rxlen.setMinimal(true); // it's lazy which means that if it finds "end" it stops and not trying to find "$" which is the end of the string
int pos = rxlen.indexIn("test start testing some text start here fdsfdsfdsend test ");

if (pos > -1) { // if the string matched, which means that "start" will be in it, followed by a string
qDebug() << rxlen.cap(2); // " testing some text start here fdsfdsfds"
}
}

即使你最后有“end”,它也能工作,然后它只解析到行尾。享受吧!

关于c++ - 如何使用 Qt 库从文本文件中获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9523730/

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