从字母数字 QString 中提取编号

Extract number from Alphanumeric QString

本文关键字:提取 编号 QString 数字      更新时间:2023-10-16

我的QString是"s150 d300"。如何从 QString 获取数字并将其转换为整数。简单地使用"toInt"是行不通的。

比方说,从">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 将被弃用,所以我提出了一个使用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)

如果你能做到,为什么会有所有的麻烦:

#include <QDebug>
#include <QString>
const auto serialNumberStr = QStringLiteral("s150 d300");
int main()
{
const QRegExp rx(QLatin1Literal("[^0-9]+"));
const auto&& parts = serialNumberStr.split(rx, QString::SkipEmptyParts);
qDebug() << "2nd nbr:" << parts[1];
}

打印输出:2nd nbr: "300"

如果您的字符串被拆分为空格分隔的标记,就像您给出的示例一样,您可以通过拆分它来简单地从中获取值,然后找到满足您需求的令牌,然后获取其中的数字部分。在将 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 执行转换。