¿Cómo especificar el método QString :: indexOF no es sensible a la cantidad de espacios entre dos palabras?

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

  •  09-12-2019
  •  | 
  •  

Pregunta

He escrito un código fuente como:

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()));
    }

}

Mi problema aquí es, que el int final= filetext.indexof (E, QT :: Caseinsensible); Con QString e = "end here";, se encuentra cuando hay exactamente tres espacios entre la palabra "FIN" y "AQUÍ".Esto es problemático, porque en el texto leí los espacios entre estas dos palabras seguramente difirmarán de vez en cuando.Además, necesito escribir ambas palabras "FIN" y "AQUÍ".Intenté reducir el problema a la base y esperar que alguien tenga una idea / solución.

¿Fue útil?

Solución

Reducir el número de interspaces a 1 usando QString::simplified() método.

Otros consejos

También podría intentarlo 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;
}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top