04月07th

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

DIY编程技术2502℃我来说两句!

在编程的时候,经常遇到要判断一个字符串中的字符是否全部是数字(0-9),本来是一个很容易实现的功能,但程序员首先会想到的是,这样简单的功能有没有现成的函数可以用呢?VB.NET中有个IsNumeric(object),C#中只有判断单个字符的Char.IsNumber(),IsNumeric可以判断double类型的数字字符串,但无法排除正负号和小数点,如果判断字符串是否是一个数的话用它挺合适,但不能用来判断字符串是否全部由数字组成的。没现成的方法了,只好自己写函数:
public static bool IsNum(String str)
{
for(int i=0;i<str.Length;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<times; 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<times; i++)
{
isNumeric.IsMatch(toBeTested);
}
end = System.Environment.TickCount;

本文出自:DIY博客园,链接:https://www.diybloghome.com/prology/761.html,转载请注明!