How can I extract numerical values from a string in Qt?
In Qt, you can use some built-in methods of QRegExp, QStringList, or QString to extract numbers from a string.
- Use QRegExp:
QString text = "Hello123World456";
QRegExp regex("\\d+"); // 匹配一个或多个数字
int pos = 0;
while ((pos = regex.indexIn(text, pos)) != -1) {
QString number = regex.cap(0); // 获取匹配到的数字
// 处理数字
qDebug() << number;
pos += regex.matchedLength();
}
- Utilize QStringList:
QString text = "Hello 123 World 456";
QStringList list = text.split(QRegExp("\\D+")); // 使用非数字字符分割字符串
foreach (const QString &number, list) {
if (!number.isEmpty()) {
// 处理数字
qDebug() << number;
}
}
- Utilizing the toInt() or toDouble() method in QString:
QString text = "Hello 123 World 456";
QString number;
int pos = 0;
while (pos < text.length()) {
if (text[pos].isDigit()) { // 找到数字的起始位置
int startPos = pos;
while (pos < text.length() && text[pos].isDigit()) {
pos++;
}
number = text.mid(startPos, pos - startPos); // 截取数字
// 处理数字
qDebug() << number;
}
pos++;
}
Please choose the method that best suits your actual needs.