从字母数字 QString 中提取编号
Extract number from Alphanumeric QString
我的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 执行转换。
相关文章:
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么istream不支持右值提取
- 如何设置一个范围来提取我想要获得的信息
- 视觉工作室项目.提取源文件夹名称
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 从 std::vector<无符号字符>切片中提取 int?
- 在C++中使用重载提取运算符时出现问题
- 在 Qt(C++) 中使用 QProcess 解压缩 - 提取目录问题
- 如何在数组中找到最小编号的索引号?
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 无法从 std::string 中提取C++ Unicode 符号
- 如何从也包含C++字母的文本文件中提取某些数字?
- 如何从适合一定范围的数字中提取数字?
- C++从通用引用中提取实际类型
- 从字母数字 QString 中提取编号
- 如何从 9 和 90 中提取 2.9 和 2.09,即获取数字等于最大编号的小数部分.二分位数之后的数字