如何检查一个QString的第一个字符?

5
我希望以下代码可以去除价格前面的零(0.00变为.00)。
QString price1 = "0.00";
if( price1.at( 0 ) == "0" ) price1.remove( 0 );

这给我带来了以下错误:"error: conversion from ‘const char [2]’ to ‘QChar’ is ambiguous"
5个回答

8
主要问题是Qt将"0"视为以空字符结尾的ASCII字符串,因此编译器会显示有关const char[2]的消息。
另外,QString::remove()需要两个参数。所以你的代码应该是:
if( price1.at( 0 ) == '0' ) price1.remove( 0, 1 );

这个在我的系统上构建并运行成功(Qt 4.7.3,VS2005)。


5
试试这个:
price1.at( 0 ) == '0' ?

2
问题在于'at'函数返回的是一个QChar对象,这个对象无法与原生的char/string "0"进行比较。你有几种选择,但我只列出其中两种:
if( price1.at(0).toAscii() == '0')

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

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


可能应该是 price1.at(0).digitValue() - jrok
1
由于QChar :: QChar(char)似乎是非显式的,因此仅使用...at(0)== '0'即可。 - Christian Rau

0
QString s("foobar");
if (s[0]=="f") {
    return;
}

0
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接