如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
当前回答
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;
}
其他回答
对于许多数据类型,您总是可以使用内置的TryParse方法来查看所讨论的字符串是否会通过。
的例子。
decimal myDec;
var Result = decimal.TryParse("123", out myDec);
结果将= True
decimal myDec;
var Result = decimal.TryParse("abc", out myDec);
结果将= False
在项目中导入Visual Basic引用并使用其信息。IsNumeric方法,如下所示,并且能够捕获浮点数以及整数,不像上面的答案只捕获int。
// Using Microsoft.VisualBasic;
var txt = "ABCDEFG";
if (Information.IsNumeric(txt))
Console.WriteLine ("Numeric");
IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false
试试下面定义的正则表达式
new Regex(@"^\d{4}").IsMatch("6") // false
new Regex(@"^\d{4}").IsMatch("68ab") // false
new Regex(@"^\d{4}").IsMatch("1111abcdefg")
new Regex(@"^\d+").IsMatch("6") // true (any length but at least one digit)
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# 7中,你可以内联out变量:
if(int.TryParse(str, out int v))
{
}