Search code examples
c++qtqstringqtcore

How to print the value of a sub-string each time it occurs in another string in Qt?


I'm working on a qt project, I have a sub-string and I want to search for this string in another string and print it each time it occurs. I have a string 1234-1456-11234-1 I want to print a each time I found 1234-1 I used the function contains but it prints the sub-string once not each time it occurs.


Solution

  • I think you are looking for the indexOf method as follows:

    main.cpp

    #include <QString>
    #include <QDebug>
    
    int main()
    {
        QString substring("substring");
        QString string("foosubstringbarsubstringbazsubstringhellosubstringworld");
        for (int i = 0; (i = string.indexOf(substring, i)) != -1; ++i)
                qDebug() << string.mid(i);
        return 0;
    }
    

    main.pro

    TEMPLATE = app
    TARGET = main
    QT = core
    SOURCES += main.cpp
    

    Build and Run

    qmake && make && ./main
    

    Output

    "substringbarsubstringbazsubstringhellosubstringworld"
    "substringbazsubstringhellosubstringworld"
    "substringhellosubstringworld"
    "substringworld"