Reputation: 5067
What is the best way to tell if a QString
is made up of just numbers?
There doesn't appear to be a convenience function in the QString
library.
Do I have to iterate over every character, one at a time, or is there a more elegant way that I haven't thought of?
Upvotes: 28
Views: 53642
Reputation: 12795
QString::toInt
Is what you looking for .
int QString::toInt(bool * ok = 0, int base = 10) const
Returns the string converted to an int using base base, which is 10 by default and must be between 2 and 36, or 0. Returns 0 if the conversion fails. If a conversion error occurs, *ok is set to false; otherwise *ok is set to true.
Example :
QString str = "FF";
bool ok;
int hex = str.toInt(&ok, 16); // hex == 255, ok == true
int dec = str.toInt(&ok, 10); // dec == 0, ok == false
Upvotes: 34
Reputation: 229934
You could use a regular expression, like this:
QRegExp re("\\d*"); // a digit (\d), zero or more times (*)
if (re.exactMatch(somestr))
qDebug() << "all digits";
Upvotes: 38
Reputation: 443
we can iterate over every character like this code:
QString example = "12345abcd";
for (int i =0;i<example.size();i++)
{
if (example[i].isDigit()) // to check if it is number!!
// do something
else if (example[i].isLetter()) // to check if it is alphabet !!
// do something
}
Upvotes: 7