【问题标题】:How do I examine the first character of a QString?如何检查 QString 的第一个字符?
【发布时间】:2011-12-06 18:27:36
【问题描述】:

我希望以下代码从价格中删除前导零(应将 0.00 削减为 .00)

QString price1 = "0.00";
if( price1.at( 0 ) == "0" ) price1.remove( 0 );

这给了我以下错误:“错误:从‘const char [2]’到‘QChar’的转换不明确”

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    主要问题是 Qt 将 "0" 视为以 null 结尾的 ASCII 字符串,因此编译器消息是关于 const char[2]

    另外,QString::remove() 接受两个参数。所以你的代码应该是:

    if( price1.at( 0 ) == '0' ) price1.remove( 0, 1 );
    

    这在我的系统上构建和运行(Qt 4.7.3,VS2005)。

    【讨论】:

      【解决方案2】:

      试试这个:

      price1.at( 0 ) == '0' ?
      

      【讨论】:

        【解决方案3】:

        问题在于'at'函数返回一个QChar,它是一个无法与原生字符/字符串“0”进行比较的对象。你有几个选择,但我这里只放两个:

        if( price1.at(0).toAscii() == '0')
        

        if( price1.at(0).digitValue() == 0)
        

        digitValue 如果 char 不是数字,则返回 -1。

        【讨论】:

        • 应该是price1.at(0).digitValue()
        • 由于QChar::QChar(char) 似乎是非显式的,所以...at(0) == '0' 也应该这样做。
        【解决方案4】:
        QString s("foobar");
        if (s[0]=="f") {
            return;
        }
        

        【讨论】:

          【解决方案5】:

          QChar QString::front() const 返回第一个字符 细绳。与 at(0) 相同。

          提供此功能是为了兼容 STL。

          警告:在空字符串上调用此函数构成 未定义的行为。

          http://doc.qt.io/qt-5/qstring.html#front

          QString s("foobar");
          
          /* If string is not empty or null, check to see if the first character equals f */
          if (!s.isEmpty() && s.front()=="f") {
              return;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-04-15
            • 1970-01-01
            相关资源
            最近更新 更多