如果我有这些字符串:

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

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


当前回答

最好的灵活解决方案是.net内置函数- char.IsDigit。它适用于无限长的数字。只有当每个字符都是数字时,它才会返回true。我使用它很多次,没有任何问题,而且我找到了更简单的解决方案。我做了一个示例方法。它可以使用了。此外,我还增加了对空输入的验证。所以这个方法现在是完全无懈可击的

public static bool IsNumeric(string strNumber)
    {
        if (string.IsNullOrEmpty(strNumber))
        {
            return false;
        }
        else
        {
            int numberOfChar = strNumber.Count();
            if (numberOfChar > 0)
            {
                bool r = strNumber.All(char.IsDigit);
                return r;
            }
            else
            {
                return false;
            }
        }
    }

其他回答

如果输入的都是数字,则返回true。不知道它是否比TryParse更好,但它会工作。

Regex.IsMatch(input, @"^\d+$")

如果您只想知道它是否有一个或多个数字与字符混合,请省略^ +和$。

Regex.IsMatch(input, @"\d")

编辑: 实际上,我认为它比TryParse更好,因为一个很长的字符串可能会溢出TryParse。

我猜这个答案会被淹没在其他答案中,但不管怎样,开始吧。

我最终通过谷歌解决了这个问题,因为我想检查字符串是否为数字,这样我就可以使用double.Parse(“123”)而不是TryParse()方法。

为什么?因为在知道解析是否失败之前,必须声明一个out变量并检查TryParse()的结果是很烦人的。我想使用三元运算符来检查字符串是否为数值,然后在第一个三元表达式中解析它或在第二个三元表达式中提供默认值。

是这样的:

var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;

它只是比:

var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
    //whatever you want to do with doubleValue
}

我为这些情况做了一些扩展方法:


可拓方法一

public static bool IsParseableAs<TInput>(this string value) {
    var type = typeof(TInput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return false;

    var arguments = new[] { value, Activator.CreateInstance(type) };
    return (bool) tryParseMethod.Invoke(null, arguments);
}

例子:

"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;

因为IsParseableAs()尝试将字符串解析为适当的类型,而不仅仅是检查字符串是否为“numeric”,所以应该是相当安全的。您甚至可以将它用于具有TryParse()方法的非数值类型,如DateTime。

该方法使用反射,最终调用TryParse()方法两次,当然,这不是那么有效,但并不是所有事情都必须完全优化,有时方便更重要。

此方法还可以用于轻松地将数字字符串列表解析为具有默认值的double或其他类型的列表,而无需捕获任何异常:

var sNumbers = new[] {"10", "20", "30"};
var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);

可拓方法二

public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
    var type = typeof(TOutput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return defaultValue;

    var arguments = new object[] { value, null };
    return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
}

这个扩展方法允许您将字符串解析为具有TryParse()方法的任何类型,它还允许您指定转换失败时要返回的默认值。

这比上面的扩展方法使用三元运算符要好,因为它只进行一次转换。它仍然使用反射…

例子:

"123".ParseAs<int>(10);
"abc".ParseAs<int>(25);
"123,78".ParseAs<double>(10);
"abc".ParseAs<double>(107.4);
"2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
"monday".ParseAs<DateTime>(DateTime.MinValue);

输出:

123
25
123,78
107,4
28.10.2014 00:00:00
01.01.0001 00:00:00
//To my knowledge I did this in a simple way
static void Main(string[] args)
{
    string a, b;
    int f1, f2, x, y;
    Console.WriteLine("Enter two inputs");
    a = Convert.ToString(Console.ReadLine());
    b = Console.ReadLine();
    f1 = find(a);
    f2 = find(b);

    if (f1 == 0 && f2 == 0)
    {
        x = Convert.ToInt32(a);
        y = Convert.ToInt32(b);
        Console.WriteLine("Two inputs r number \n so that addition of these text box is= " + (x + y).ToString());
    }
    else
        Console.WriteLine("One or two inputs r string \n so that concatenation of these text box is = " + (a + b));
    Console.ReadKey();
}

static int find(string s)
{
    string s1 = "";
    int f;
    for (int i = 0; i < s.Length; i++)
       for (int j = 0; j <= 9; j++)
       {
           string c = j.ToString();
           if (c[0] == s[i])
           {
               s1 += c[0];
           }
       }

    if (s == s1)
        f = 0;
    else
        f = 1;

    return f;
}

你还可以使用:

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不应该是空字符串,因为这将通过是否是数字的测试。

这可能是c#中最好的选择。

如果你想知道字符串是否包含一个整数(整数):

string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);

TryParse方法将尝试将字符串转换为一个数字(整数),如果成功,它将返回true并将相应的数字放在myInt中。如果不能,则返回false。

使用其他响应中显示的int.Parse(someString)替代方法的解决方案是可行的,但它要慢得多,因为抛出异常的代价非常高。TryParse(…)在版本2中被添加到c#语言中,在此之前您没有选择。现在您做到了:因此应该避免使用Parse()替代方法。

如果你想接受十进制数,decimal类还有一个. tryparse(…)方法。在上面的讨论中,将int替换为decimal,同样的原则也适用。