我知道一些方法来检查字符串是否只包含数字: 正则表达式,int。解析,tryparse,循环等等。

谁能告诉我最快的方法是什么?

我只需要检查值,不需要实际解析它。

通过“数字”,我是指具体的ASCII数字:0 1 2 3 4 5 6 7 8 9。

如果字符串是数字,这个问题与Identify不同,因为这个问题不仅是关于如何识别,而且是关于识别的最快方法是什么。


当前回答

这很好,还有很多其他的方法,但这个也行

bool IsDigitsOnly(string str)
    {
        if (str.Length > 0)//if contains characters
        {
            foreach (char c in str)//assign character to c
            {
                if (c < '0' || c > '9')//check if its outside digit range
                    return false;
            }
        }else//empty string
        {
            return false;//empty string 
        }

        return true;//only digits
    }

其他回答

我喜欢Linq,让它在第一次不匹配时退出,你可以这样做

string str = '0129834X33';
bool isAllDigits = !str.Any( ch=> ch < '0' || ch > '9' );

可能最快的方法是:

myString.All(c => char.IsDigit(c))

注意:如果你的字符串是空的,它将返回True,这是不正确的(如果你不认为空是有效的数字/数字)

函数的空验证:

public static bool IsDigitsOnly(string str)
  {             
        return !string.IsNullOrEmpty(str) && str.All(char.IsDigit);
  }

那么char.IsDigit(myChar)呢?

如果是单个字符串:

if (str.All(Char.IsDigit))
{
  // string contains only digits
}

如果是字符串列表:

if (lstStr.All(s => s.All(Char.IsDigit)))
{
  // List of strings contains only digits
}