一聚教程网:一个值得你收藏的教程网站

热门教程

判断一个字符串是否全是数字的多种方法及其性能比较(C#实现)

时间:2022-07-02 11:08:29 编辑:袖梨 来源:一聚教程网

在编程的时候,经常遇到要判断一个字符串中的字符是否全部是数字(0-9),本来是一个很容易实现的功能,但程序员首先会想到的是,这样简单的功能有没有现成的函数可以用呢?VB.NET中有个IsNumeric(object),C#中只有判断单个字符的Char.IsNumber(),IsNumeric可以判断double类型的数字字符串,但无法排除正负号和小数点,如果判断字符串是否是一个数的话用它挺合适,但不能用来判断字符串是否全部由数字组成的。没现成的方法了,只好自己写函数:
public static bool IsNum(String str)
{
for(int i=0;i {
if(!Char.IsNumber(str,i))
return false;
}
return true;
}
或用正则表达式:"^d+$"
还可以用Int32.Parse()抛出的Exception来判断:
try
{
Int32.Parse(toBeTested);
}
catch
{
//发生了异常,那么就不是数字了。
}
那么哪一种方法最好呢?各有优劣。我顺手写了一个程序对每一种方法所需要的时间进行了测试。测试程序Main()内容如下:
Regex isNumeric = new Regex(@"^d+$");
int times = 10000000;
int start, end;
int i;
string toBeTested = "6741s";
#region Test user function
start = System.Environment.TickCount;
for(i=0; i{
TimingTest.IsNum(toBeTested);
}
end = System.Environment.TickCount;
Console.WriteLine("User function Time: " + (end-start)/1000.0 + " Seconds");
#endregion
#region Test Regular Expression
start = System.Environment.TickCount;
for(i=0; i{
isNumeric.IsMatch(toBeTested);
}
end = System.Environment.TickCount;

热门栏目