How to specify the QString::indexOf method?

15,063

The declaration of indexOf of QString is the following:

int QString::indexOf ( const QString & str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const

If you take a look you'll see that there is one more parameter than the one you use in your call to indexOf. This is because it has a default value and it is the argument:

int from = 0

This from is by default set to 0 so that whenever you ommit this value the search is done from the beginning of the string, but you can set its value to the index where you found the "start" word just like this:

int start = x.indexOf(s, 0, Qt::CaseInsensitive); 
int end = x.indexOf(e, start, Qt::CaseInsensitive); //notice the use of start as the 'from' argument

This way you are going to get the index of the first "end" word that comes after the first "start" word. Hope this helps!

Share:
15,063
Streight
Author by

Streight

Study machine- and process-engineering, Greetings from Germany

Updated on July 31, 2022

Comments

  • Streight
    Streight almost 2 years

    I have written a source code like:

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

    The problem is, that in my textfile the word "end" is found very very often. So, is there a way to create a indexOf method that just searchs for the FIRST " QString e = "end" " that appears after the "QString s = "start" " ? greetings