Como obter uma String de um arquivo de texto com bibliotecas Qt
Pergunta
Quero obter algumas Strings de um arquivo de texto.Eu sei como obter toda a String de um arquivo de texto com
QTextStream Stream (GEO);
QString text;
do
{
text = Stream.readLine();
}
while(!text.isNull());
Isso funciona bem para obter todo o texto sob o texto QString, mas eu só preciso de algumas strings específicas do texto, esquematicamente como:
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
Alguém pode me dizer como fazer isso ou talvez até me dar um pequeno exemplo?
Solução
Uma coisa que você pode usar é obter os índices de "início" e "fim" com indexOf() e apenas usar:
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);
ou midRef se não quiser criar uma nova lista.Talvez você precise lidar com "end" também, caso contrário, poderá ir de 0 a -1, o que não retornaria nada.Talvez (fim > início?fim :começar)
Editar:Deixa para lá.Se end == -1 isso significa apenas que retornará tudo até o final (por padrão, o segundo parâmetro é -1).Se você não quiser isso, você pode seguir meu exemplo e usar algum tipo de instrução if ao escolher o "fim"
Editar:Percebi que li mal o documento e isso será definitivamente.trabalhar:
#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()));
}
}
Isso produz os seguintes resultados.Os dois últimos números são onde termina "início" e começa "fim".
x = "comece algum texto aqui end" => "algum texto aqui" 5 16
x = "algum texto aqui no final" => sem impressão
x = "testing start iniciar algum texto aqui end" => "iniciar algum texto aqui" 13 22
x = "testing start start algum texto aqui" => "start algum texto aqui" 13 -14
Ou você pode fazer isso usando regEx.Escrevi um trecho bem simples aqui para você:
#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"
}
}
Isso funciona mesmo se você tiver "end" no final, então basta analisar até o final da linha.Aproveitar!