如果我有这些字符串:

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

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


当前回答

我知道这是一个老线程,但是没有一个答案真的对我有用——要么效率低,要么没有被封装以便于重用。我还想确保它在字符串为空或null时返回false。在这种情况下,TryParse返回true(当解析为数字时,空字符串不会导致错误)。这是我的字符串扩展方法:

public static class Extensions
{
    /// <summary>
    /// Returns true if string is numeric and not empty or null or whitespace.
    /// Determines if string is numeric by parsing as Double
    /// </summary>
    /// <param name="str"></param>
    /// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
    /// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
    /// <returns></returns>
    public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
        CultureInfo culture = null)
    {
        double num;
        if (culture == null) culture = CultureInfo.InvariantCulture;
        return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
    }
}

使用简单:

var mystring = "1234.56789";
var test = mystring.IsNumeric();

或者,如果你想测试其他类型的数字,你可以指定“样式”。 所以,要用指数转换一个数字,你可以使用:

var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);

或者要测试一个潜在的十六进制字符串,你可以使用:

var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)

可选的'culture'参数也可以以大致相同的方式使用。

它的限制是不能转换太大而不能包含在double类型中的字符串,但这是一个有限的要求,我认为如果你处理的数字比这个大,那么你可能需要额外的专门的数字处理函数。

其他回答

int n;
bool isNumeric = int.TryParse("123", out n);

从c# 7开始更新:

var isNumeric = int.TryParse("123", out int n);

或者,如果不需要这个数字,可以丢弃out参数

var isNumeric = int.TryParse("123", out _);

变量可以被它们各自的类型替换!

下面是c#方法。 Int。TryParse方法(String, Int32)

如果输入的都是数字,则返回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;
}