Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a QString is made up of all numeric characters?

Tags:

c++

qt

qt4

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?

like image 659
Wes Avatar asked Jan 09 '12 16:01

Wes


People also ask

Can a char contain numbers?

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.

How do you test if a string is a number C++?

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.


3 Answers

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";
like image 55
sth Avatar answered Oct 03 '22 11:10

sth


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
like image 43
Alexander Avatar answered Oct 03 '22 11:10

Alexander


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
}
like image 21
Mohamed A M-Hassan Avatar answered Oct 03 '22 11:10

Mohamed A M-Hassan