要求123+456+789,需要先将字符串中的数字提取出来,然后进行相加操作。

在Qt中,可以使用正则表达式来提取字符串中的数字。以下是一个示例代码:

#include <QCoreApplication>
#include <QString>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString str = "Qt 字符串&123&%456&(789##";

    // 匹配数字的正则表达式
    QRegularExpression re("\\d+");

    // 在字符串中查找匹配的数字
    QRegularExpressionMatchIterator i = re.globalMatch(str);

    int sum = 0;

    // 遍历匹配的结果,并将数字相加
    while (i.hasNext()) {
        QRegularExpressionMatch match = i.next();
        QString numStr = match.captured();
        int num = numStr.toInt();
        sum += num;
    }

    qDebug() << "123 + 456 + 789 = " << sum;

    return a.exec();
}

运行以上代码,输出结果为:123 + 456 + 789 = 1368

Qt 字符串&123&456&789## 求123+456+789

原文地址: http://www.cveoy.top/t/topic/i7A7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录