1
該檢查不得使用用戶C++ 11功能或其他庫例如提升,正則表達式等我提出了以下解決方案。沒有漂亮,但工作。它從這裏變得更優雅和/或更快嗎?確定字符串是否爲JSON編號的快速方法
bool isJsonNumber(const std::string& text)
{
if(text.empty()) return false;
bool foundE = false;
bool foundESign = false;
bool leadingZero = false;
bool lastIsDigit = false;
bool foundDot = false;
for(uint32_t i=0; i < text.length(); ++i)
{
const unsigned char c = text[i];
lastIsDigit = false;
const bool currIsNoDigit = (c < '0' || c > '9');
if(i == 0)
{
if(currIsNoDigit && c != '-') return false;
if(c == '0') leadingZero = true;
if(c != '-') lastIsDigit = true;
}
else
{
if(leadingZero)
{
leadingZero = false;
if(c != '.') return false;
foundDot = true;
}
else if(c == '.')
{
if(foundDot) return false;
foundDot = true;
}
else if(c == 'e' || c == 'E')
{
if(foundE) return false;
foundE = true;
}
else if(foundE && !foundESign)
{
if(currIsNoDigit && c != '-' && c != '+') return false;
if(c == '+' || c == '-')
{
foundESign = true;
}
else
{
lastIsDigit = true;
}
}
else
{
foundESign = false;
if(currIsNoDigit) return false;
lastIsDigit = true;
}
}
}
if(lastIsDigit == false) return false;
return true;
}
該用例是一個小型的嵌入式服務器,它接收大量的CSV文件和帶有JSON部分的awsers客戶端。
JSON規範描述了可以超過雙倍大小的任意大小的數字。 Infinity和NaN也不是數字的允許值,對於十六進制數字也是一樣的。 std :: stod也是C++ 11 – aggsol 2013-03-22 09:39:08
函數std :: strtod不適合驗證JSON數字。規範可以在RFC 4627中找到。OP的版本(可能)是OK的。 (假設有相應的單元測試;)) – CouchDeveloper 2013-03-28 11:42:19