如果我有这些字符串:

"abc" =假 "123" =真 "ab2" = false

是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?


当前回答

在c# 7中,你可以内联out变量:

if(int.TryParse(str, out int v))
{
}

其他回答

你还可以使用:

using System.Linq;

stringTest.All(char.IsDigit);

它将返回true对于所有数字(不是浮点)和false如果输入字符串是任何类型的字母数字。

Test case Return value Test result
"1234" true ✅Pass
"1" true ✅Pass
"0" true ✅Pass
"" true ⚠️Fail (known edge case)
"12.34" false ✅Pass
"+1234" false ✅Pass
"-13" false ✅Pass
"3E14" false ✅Pass
"0x10" false ✅Pass

请注意:stringTest不应该是空字符串,因为这将通过是否是数字的测试。

对于许多数据类型,您总是可以使用内置的TryParse方法来查看所讨论的字符串是否会通过。

的例子。

decimal myDec;
var Result = decimal.TryParse("123", out myDec);

结果将= True

decimal myDec;
var Result = decimal.TryParse("abc", out myDec);

结果将= False

 bool is_number(string str, char delimiter = '.')
    {
        if(str.Length==0) //Empty
        {
            return false;
        }
        bool is_delimetered = false;
        foreach (char c in str)
        {
            if ((c < '0' || c > '9') && (c != delimiter)) //ASCII table check. Not a digit && not delimeter
            {
                return false;
            }
            if (c == delimiter)
            {
                if (is_delimetered) //more than 1 delimiter
                {
                    return false;
                }
                else //first time delimiter
                {
                    is_delimetered = true;
                }
            }
        }
        return true; 
    }

以防你不想用int。解析或双重。解析,你可以用这样的东西来滚动你自己的:

public static class Extensions
{
    public static bool IsNumeric(this string s)
    {
        foreach (char c in s)
        {
            if (!char.IsDigit(c) && c != '.')
            {
                return false;
            }
        }

        return true;
    }
}

翻倍。TryParse

bool Double.TryParse(string s, out double result)