PDA

View Full Version : How to count numbers in the end of QString



naptizaN
17th July 2012, 13:35
Hello again, sorry for beginners question but I need to count numbers in the end of QString. The format of QString is different like B9_02 (must get result of 2 from here) or TP145 (and 3 from here).
What function should i use to get the count of numbers?

amleto
17th July 2012, 14:03
Start from the back of the string and check each (Q)char if it is a number (QChar#isNumber). If it is, add 1 to a count.

the first non-number that you find (or start of string), then stop the count.

zgulser
17th July 2012, 14:04
QChar::isDigit

amleto
17th July 2012, 14:14
ah yes, isDigit is better than isNumber in this case.

naptizaN
18th July 2012, 07:18
Trying such a code:

QString p=le2->text();
int count = 0;
for(int j = p.length(); j > 0; j--)
{
if (p.at(j).isDigit()==true)
count++;
if (p.at(j).isDigit()==false)
break;
}
qDebug() << "count" << count;
But get such an error: ASSERT: "i >= 0 && i < size()" in file ../../../../Qt/Desktop/Qt/473/gcc/include/QtCore/qstring.h, line 702
Can you help me and write what i am doing wrong? using p[j] gives no error but gives no result (count =0 in any case).

ChrisW67
18th July 2012, 07:50
If the string length is 5 then the character indexes are 0 through 4. Try starting with character length() - 1.