【问题标题】:Extract number from Alphanumeric QString从字母数字 QString 中提取数字
【发布时间】:2018-01-01 05:21:21
【问题描述】:

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

比方说,从 "s150 d300" 的 QString 中,只有字母 'd' 后面的 数字对我来说是有意义的。那么如何从字符串中提取 '300' 的值呢?

非常感谢您的宝贵时间。

【问题讨论】:

    标签: c++ qt integer qt5 alphanumeric


    【解决方案1】:

    如果你能做到,为什么还要麻烦:

    #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"

    【讨论】:

      【解决方案2】:

      一种可能的解决方案是使用如下所示的正则表达式:

      #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会是deprecated,所以我提出了一个使用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)
      

      【讨论】:

      【解决方案3】:

      如果你的字符串被分割成空格分隔的标记,就像你给出的例子一样,你可以简单地通过分割它来获取它的值,然后找到一个满足你需要的标记,然后取它的数字部分。在将 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);
      }
      

      【讨论】:

        【解决方案4】:

        已经有答案为这个问题提供了合适的解决方案,但我认为强调QString::toInt 不起作用可能也会有所帮助,因为要转换的字符串应该是数字的文本表示形式并且在给定的例如,它是一个非标准符号的字母数字表达式,因此有必要按照已经建议的方式手动处理它,以使 Qt 执行转换“可理解”。

        【讨论】:

          猜你喜欢
          • 2018-02-05
          • 1970-01-01
          • 1970-01-01
          • 2017-07-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-30
          • 2014-01-20
          相关资源
          最近更新 更多