C++ 如何检测 QString 是否由所有数字字符组成?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8791380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect if a QString is made up of all numeric characters?
提问by Wes
What is the best way to tell if a QString
is made up of just numbers?
判断 aQString
是否仅由数字组成的最佳方法是什么?
There doesn't appear to be a convenience function in the QString
library.
库中似乎没有便利功能QString
。
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?
我是否必须一次迭代一个角色,还是有一种我没有想到的更优雅的方式?
回答by sth
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";
回答by Alexander
QString::?toInt
Is what you looking for .
QString::?toInt
是你要找的。
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.
返回使用 base base 转换为 int 的字符串,默认情况下为 10,并且必须介于 2 和 36 之间,或 0。如果转换失败,则返回 0。如果发生转换错误,*ok 设置为 false;否则 *ok 设置为 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
回答by Mohamed A M-Hassan
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
}