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?
The CHAR data type stores any string of letters, numbers, and symbols. It can store single-byte and multibyte characters, based on the database locale. The CHARACTER data type is a synonym for CHAR.
Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.
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";
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With