从字母数字QString中提取数字
问题描述:
我有一个QString为“s150 d300”。我如何从QString获取数字并将其转换为整数。简单地使用'toInt'不起作用。从字母数字QString中提取数字
让说,从“S150 D300”的QString的,只有字母“d”后数量是有意义的我。那么如何从字符串中提取'300'的值呢?
非常感谢您的时间。
答
一种可能的解决方案是使用正则表达式,如下所示:
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString str = "s150 dd300s150 d301d302s15";
QRegExp rx("d(\\d+)");
QList<int> list;
int pos = 0;
while ((pos = rx.indexIn(str, pos)) != -1) {
list << rx.cap(1).toInt();
pos += rx.matchedLength();
}
qDebug()<<list;
return a.exec();
}
输出:
(300, 301, 302)
由于@IlBeldus的评论,并根据该信息QRegExp将deprecated,所以我建议使用QRegularExpression
的解决方案:
另一种解决方案:
QString str = "s150 dd300s150 d301d302s15";
QRegularExpression rx("d(\\d+)");
QList<int> list;
QRegularExpressionMatchIterator i = rx.globalMatch(str);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
QString word = match.captured(1);
list << word.toInt();
}
qDebug()<<list;
输出:
(300, 301, 302)
答
如果字符串被分成就像你给了你可以简单地通过拆分它,然后找到能够满足您需求的令牌获得价值了它的例子空间分隔的记号然后把它的数字部分。在将qstring转换为我更舒适的东西之后,我使用了atoi,但我认为这是一种更有效的方法。
虽然这不像正则表达式那样灵活,但它应该为您提供的示例提供更好的性能。
#include <QCoreApplication>
int main() {
QString str = "s150 d300";
// foreach " " space separated token in the string
for (QString token : str.split(" "))
// starts with d and has number
if (token[0] == 'd' && token.length() > 1)
// print the number part of it
qDebug() <<atoi(token.toStdString().c_str() + 1);
}
答
现在已经有解答了给一个合适的解决这个问题,但我认为这可能是也很有帮助强调,QString::toInt
不会起作用,因为该字符串被转换应该是在一些与文字表述给出的例子是一个非标准表示法中的字母数字表达式,因此有必要按照已经建议的那样手动处理它,以便让Qt执行转换“不可扩展”。
QRegExp在Qt5中不推荐使用,应该使用QRegularExpression。来自Qt论坛的重复问题:https://forum.qt.io/topic/81717/extract-number-from-an-alphanumeric-qstring – IlBeldus
这两个版本仍然支持,看看这个:http://doc.qt。 io/qt-5/qregexp.html和http://doc.qt.io/qt-5/qregularexpression.html。 – eyllanesc
另外它不是重复的,我已经在2小时前回复了,相反论坛已经在15分钟前解决了。 – eyllanesc