I have a QString of "s150 d300". How can I get the numbers from the QString and convert it into integer. Simply using 'toInt' is not working.
Let say, from the QString of "s150 d300", only the number after the alphabet 'd' is meaningful to me. So how can I extract the value of '300' from the string?
Thank you very much for your time.
Why all the trouble if you can just do:
#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];
}
Prints out: 2nd nbr: "300"
One possible solution is to use regular expressions as shown below:
#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();
}
Output:
(300, 301, 302)
Thanks to the comment of @IlBeldus, and according to the information QRegExp will be deprecated, so I propose a solution using QRegularExpression:
Another solution:
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;
Output:
(300, 301, 302)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With