Search code examples
c++qstringqt5.6lastindexof

Qt QString lastIndexOf not working


I'm using Qt5.6, I'm trying to use the QString function lastIndexOf. The subject data contains something like:

    156 + (28 * 4) + (14 * 9 * 2)

Using indexOf:

    int intOpB = strLocalCopy.indexOf(ucOpenBracket);

strLocalCopy contains the subject data and ucOpenBracket contains '('.

intOpB is returned correctly and is 6.

I then look for the last occurence of ')':

    int intClB = strLocalCopy.lastIndexOf(ucCloseBracket, (++intOpB));

Using intOpB as a reference, but lastIndexOf is always returning -1 to intClB, why?

I'm using the debugger to single step so I can verify that all variables contain what they should.

If I remove the 2nd parameter it works, but I don't understand why it doesn't work with the parameter supplied.


Solution

  • From the Documentation:

    int QString::lastIndexOf(const QString &str, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

    Returns the index position of the last occurrence of the string str in this string, searching backward from index position from. If from is -1 (default), the search starts at the last character; if from is -2, at the next to last character and so on. Returns -1 if str is not found.

    If cs is Qt::CaseSensitive (default), the search is case sensitive; otherwise the search is case insensitive.

    So the search starts from position 7 and searches BACKWARDS for the last occurence of ')', which at that point there are none between positions 0-7 on the QString