如何解决用于检查字符串是否为数字的c#代码
| 我正在使用Visual Studio 2010,我想检查字符串是否为数字,是否有内置函数来检查此字符,还是需要编写自定义代码?解决方法
您可以使用int.TryParse方法。例:
string s = ...
int result;
if (int.TryParse(s,out result))
{
// The string was a valid integer => use result here
}
else
{
// invalid integer
}
除整数外,还有其他数字类型的float.TryParse,double.TryParse和decimal.TryParse方法。
但是,如果这是出于验证目的,则还可以考虑使用ASP.NET中的内置“验证”控件。这是一个例子。
,你可以喜欢...
string s = \"sdf34\";
Int32 a;
if (Int32.TryParse(s,out a))
{
// Value is numberic
}
else
{
//Not a valid number
}
,您可以使用Int32.TryParse()
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
,是的,有:int.TryParse(...)
检查out bool
参数。
,看一下这个问题:
NaN或IsNumeric的C#等效项是什么?
,您可以使用内置方法Int.Parse或Double.Parse方法。您可以编写以下函数,并在需要时调用以对其进行检查。
public static bool IsNumber(String str)
{
try
{
Double.Parse(str);
return true;
}
catch (Exception)
{
return false;
}
}
,所有Double / Int32 / ...TryParse(...)
方法的问题在于,如果数字字符串足够长,该方法将返回false;否则,该方法将返回false。
例如:
var isValidNumber = int.TryParse(\"9999999999\",out result);
尽管给定的字符串是数字,但isValidNumber
为假,result
为0。
如果您不需要将字符串用作int,那么我将对正则表达式进行验证:
var isValidNumber = Regex.IsMatch(input,@\"^\\d+$\")
这只会匹配整数。例如,““ 123.45 \”将失败。
如果需要检查浮点数:
var isValidNumber = Regex.IsMatch(input,@\"^[0-9]+(\\.[0-9]+)?$\")
注意:尝试创建单个Regex
对象,并将其发送给int测试方法以提高性能。
,尝试这个:
string Str = textBox1.Text.Trim();
double Num;
bool isNum = double.TryParse(Str,out Num);
if (isNum)
MessageBox.Show(Num.ToString());
else
`enter code here`MessageBox.Show(\"Invalid number\");
,使用IsNumeric()检查给定的字符串是否为数字。无论数值是Int还是Double,它总是返回True。
string val=...;
bool b1 = Microsoft.VisualBasic.Information.IsNumeric(val);
,using System;
namespace ConsoleApplication1
{
class Test
{
public static void Main(String[] args)
{
bool check;
string testStr = \"ABC\";
string testNum = \"123\";
check = CheckNumeric(testStr);
Console.WriteLine(check);
check = CheckNumeric(testNum);
Console.WriteLine(check);
Console.ReadKey();
}
public static bool CheckNumeric(string input)
{
int outPut;
if (int.TryParse(input,out outPut))
return true;
else
return false;
}
}
}
这将为您工作!
,试试这个->
String[] values = { \"87878787878\",\"676767676767\",\"8786676767\",\"77878785565\",\"987867565659899698\" };
if (Array.TrueForAll(values,value =>
{
Int64 s;
return Int64.TryParse(value,out s);
}
))
Console.WriteLine(\"All elements are integer.\");
else
Console.WriteLine(\"Not all elements are integer.\");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。