Lady Be Good
Lady Be Good

Reputation: 271

Qt 5.15.2, C++ QString indexOf() function problem

I am using Qt Creator to develop a C++ application, I am trying to learn QString functions and i have problem with indexOf() function. I try to find "str" string in another string but this function always return the first index

#include <QString>
#include <QDebug>
int main()
{
    QString str = "Topic of today is QString String";
    QString y = "Str";
    int index;
    index = str.indexOf(y, 1);
    qDebug() << "index: " << index;
}

Upvotes: 1

Views: 1130

Answers (2)

drescherjm
drescherjm

Reputation: 10857

It always returns the first index because you use 1 as the second parameter of indexOf(). When you want the second match you need to use the previous index as the second parameter.

The following code shows how to find and display the first 2 matches.

#include <QString>
#include <QDebug>
int main()
{
    QString str = "Topic of today is QString String";
    QString y = "Str";
    int index = 0;
    index = str.indexOf(y, index);
    qDebug() << "First index: " << index;
    if (index > 0) {
       index = str.indexOf(y, index+1);
       if (index > 0) qDebug() << "Second index: " << index;
    }
}

Upvotes: 2

lostbard
lostbard

Reputation: 5230

indexOf returns the first index that matches from the startfrom offset you gave (1).

If you want to get all indexes, you need to call indexOf with the startfrom set to the last index found + 1 repeatedly until you find no more occurrences.

Upvotes: 1

Related Questions