Come specificare il metodo QString :: Indexof non essere sensibile al numero di spazi tra due parole?

StackOverflow https://stackoverflow.com//questions/9622918

  •  09-12-2019
  •  | 
  •  

Domanda

Ho scritto un codice sorgente come:

int main(int argc, char *argv[]) {
    QFile File (directory + "/File");

        if(File.open(QIODevice::ReadOnly | QIODevice::Text))
        {
         QTextStream Stream (&File);
         QString FileText;
           do
            {
      FileText = Stream.readLine();
    QString s = "start";
    QString e = "end   here";
    int start = FileText.indexOf(s, 0, Qt::CaseInsensitive); 
    int end = FileText.indexOf(e, Qt::CaseInsensitive); 

    if(start != -1){ // we found it

        QString y = FileText.mid(start + s.length(), (end - (start + s.length()))); 

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

}

Il mio problema qui è, che INT End= FileText.indexof (E, Qt :: caseinsensitive); Con QString e = "end here"; si trova appena quando ci sono esattamente tre spazi tra la parola "fine" e "qui".Questo è problematico, perché nel testo ho letto gli spazi tra queste due parole sarà sicuramente differire di volta in volta.Inoltre ho bisogno di scrivere entrambe le parole "fine" e "qui".Ho provato a ridurre il problema alla base e spero che qualcuno abbia un'idea / soluzione.

È stato utile?

Soluzione

Ridurre il numero di inter-spazi a 1 usando QString::simplified() Metodo.

Altri suggerimenti

Puoi anche provare qregexp :

#include <QDebug>
#include <QString>
#include <QRegExp>

int main()
{
    QString text("start ABCDE1234?!-: end  here foo bar");

    // create regular expression
    QRegExp rx("start\\s+(.+)\\s+end\\s+here", Qt::CaseInsensitive);

    int pos=0;

    // look for possible matches
    while ((pos=rx.indexIn(text, pos)) != -1) {
        qDebug() << rx.cap(1); // get first match in (.+)
        pos+=rx.matchedLength();
    }

    return 0;
}
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top