如果我有这些字符串:

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

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


当前回答

 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; 
    }

其他回答

这可能是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,同样的原则也适用。

以防你不想用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;
    }
}
public static bool IsNumeric(this string input)
{
    int n;
    if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
    {
        foreach (var i in input)
        {
            if (!int.TryParse(i.ToString(), out n))
            {
                return false;
            }

        }
        return true;
    }
    return false;
}

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

我最终通过谷歌解决了这个问题,因为我想检查字符串是否为数字,这样我就可以使用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

如果你想检查一个字符串是否是一个数字(我假设它是一个字符串,因为如果它是一个数字,你知道它是1)。

没有正则表达式和 尽可能多地使用微软的代码

你还可以:

public static bool IsNumber(this string aNumber)
{
     BigInteger temp_big_int;
     var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
     return is_number;
}

这将解决通常的麻烦:

开头是负(-)或正(+ BigIntegers不会解析带小数点的数字。(因此:BigInteger.Parse("3.3")将抛出异常,而TryParse将返回false) 没有搞笑的非数字 适用于数字大于Double通常用法的情况。TryParse

您必须向System添加一个引用。数字和有 使用System.Numerics;名列全班第一(好吧,我猜第二名是额外奖励:)