c#你怎么判断一个字符串是否是数字?
2010-09-30 22:38:46 来源:WEB开发网测试的代码:
class Program
{
static void Main(string[] args)
{
Test("1234");
Test("1234a");
Test("a1234");
Test("");
Test(null);
}
static void Test(string str)
{
bool res1 = false, res2 = false, res3 = false, res4 = false, res5 = false;
Stopwatch wat = new Stopwatch();
wat.Start();//杯具,这句话之前写这个测试demo的时候漏了,我说怎么全是0呢
for (int i = 1; i < 100000; i++)
{
res1 = str.isNumberic1();
}
wat.Stop();
Console.WriteLine("isDigit {0}:{1},{2}", str, wat.ElapsedMilliseconds, res1);
wat.Reset();
wat.Start();
for (int i = 1; i < 100000; i++)
{
res2= str.isNumberic2();
}
wat.Stop();
Console.WriteLine("isNumberic {0}:{1},{2}", str, wat.ElapsedMilliseconds, res2);
wat.Reset();
wat.Start();
for (int i = 1; i < 100000; i++)
{
res3 = str.isNumberic3();
}
wat.Stop();
Console.WriteLine("try parse {0}:{1},{2}", str, wat.ElapsedMilliseconds, res3);
wat.Reset();
wat.Start();
for (int i = 1; i < 100000; i++)
{
res4 = str.isNumberic4();
}
wat.Stop();
Console.WriteLine("try catch {0}:{1},{2}", str, wat.ElapsedMilliseconds, res4);
wat.Reset();
wat.Start();
for (int i = 1; i < 100000; i++)
{
res5 = str.isNumberic5();
}
wat.Stop();
Console.WriteLine("regex {0}:{1},{2}", str, wat.ElapsedMilliseconds, res5);
Console.WriteLine();
}
}
下面是我本机的测试结果
isDigit 1234:5,True
isNumberic 1234:166,True
try parse 1234:21,True
try catch 1234:22,True
regex 1234:134,True
isDigit 1234a:5,False
isNumberic 1234a:196,False
try parse 1234a:19,False
try catch 1234a:5182,False
regex 1234a:150,False
isDigit a1234:2,False
isNumberic a1234:184,False
try parse a1234:16,False
try catch a1234:5084,False
regex a1234:106,False
isDigit :1,False
isNumberic :0,False
try parse :0,False
try catch :1,False
regex :0,False
isDigit :1,False
isNumberic :0,False
try parse :1,False
try catch :1,False
regex :0,False
结果:循环判断是否是数字字符效率是最高的
而VisualBasic的方法效率比较低了
顺便测试了下VisualBasic里的left和right方法效率也一样的低,还不及substring的十分之一
所以VisualBasic里虽然有几个方法从名字看来比较好用,实际却比较杯具。
更多精彩
赞助商链接