C++ one liner for"由数字组成的字符串"

W2a*_*W2a 1 c++ c++11

我正在寻找一个短(和快)代码来检查一个字符串是否只包含数字,特别是寻找一个衬里.这是我的临时代码:

bool IsNumber(const std::string& str)
{
    int i = 0;
    for( ; i<str.size() && isdigit(str[i]); ++i);

    return ( i == str.size() );
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*zie 6

使用std :: all_of以及isdigit:

#include <algorithm>
#include <cctype>
//..
bool allDigits = (!str.empty() && std::all_of(str.begin(), str.end(), ::isdigit));
Run Code Online (Sandbox Code Playgroud)

编辑:添加了空字符串的检查.

  • @ChristianHackl - `std :: all_of`为空范围返回`true`. (2认同)
  • @RustyX这不是因为性能.在逻辑中,对于空集,谓词始终适用于其所有元素:请参阅https://en.wikipedia.org/wiki/Vacuous_truth. (2认同)