[SOLVED] Extract numbers from QString



  • Hey there,

    should be simple, but I'm very new to Qt and my brain is just overloaded with that huge amount of functions and classes and other Qt-stuff. :D

    I have a QString:

    @QString str("1 2 3 9 7 5 29 22 9f");@

    I want to extract all numbers from this QString, seperated by whitespace. See the "9f" in the end? This 9 should NOT be extracted, just numbers with whitespace before and after them. No extraction for you, f.
    The numbers should be pushed into a std::vector, for working with some library functions.

    Thank you,

    Ceriana


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You could create a QStringList with QString::split() using the space as a separator. Then loop on the list using toInt(bool *ok) to retrieve the number value (which should fail for 9F since it would be hexadecimal).

    Hope it helps


  • Moderators

    use QRegExp and define a suitable pattern and search for it.

    Or use this:
    @
    QString str("1 2 3 9 7 5 29 22 9f");
    foreach( QString numStr, str.split(" ", QString::SkipEmptyParts) )
    {
    bool check = false;
    int val = numStr.toInt(&check, 10);
    if( !check )
    continue;
    else
    //do something with "val"
    }
    @

    Edit: again SGaist was 20 secs faster :P



  • The following QRegExp should work to find all sequences of numeric characters (0-9) that are preceded by at least one whitespace and that are followed by at least one whitespace. We use it in a loop to find them all:

    @QRegExp rx("\s(\d+)\s");
    std::vector<int> result;
    int pos = 0;
    while ((pos = rx.indexIn(str, pos)) != -1)
    {
    QString theNumber = rx.cap(1);
    cout << """ << theNumber.toLatin1().constData() << """ << endl;
    result.push_back(theNumber.toInt());
    pos += rx.matchedLength();
    }@

    To handle also handle the special case where the number is located at the very beginning of the string (with no whitespace in front) or at the very end of the string (with no trailing whitespace), you'd need these too:

    @QRegExp rx_begin("^(\d+)\s");
    QRegExp rx_end("\s(\d+)$");@

    --

    Update:

    You probably could simplify all three cases to:

    @QRegExp rx("\b(\d+)\b");
    std::vector<int> result;
    int pos = 0;
    while ((pos = rx.indexIn(str, pos)) != -1)
    {
    QString theNumber = rx.cap(1);
    cout << """ << theNumber.toLatin1().constData() << """ << endl;
    result.push_back(theNumber.toInt());
    pos += rx.matchedLength();
    }@



  • I tested all three ways and got it to work as intended. Thank you guys :)


  • Lifetime Qt Champion

    You're welcome !

    Don't forget to update the thread's title to solved since all seems working now so other forum users may know a solution has been found :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.