最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
判断一个字符串是否全是数字的多种方法及其性能比较(C#实现)
时间:2008-01-12 编辑:简简单单 来源:一聚教程网
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;
-
上一个: ASP.NET中实现模版的动态加载
-
下一个: 在ASP.NET中使用用户控件
相关文章
- C#复制数组的两种方式及效率比较解读 10-24
- ASP.NET Identity用法解析 10-24
- ASP.NET MVC使用Identity增删改查用户介绍 10-24
- C语言中atoi函数模拟实现介绍 10-18
- .Net反向代理组件Yarp用法介绍 10-10
- .NET使用YARP通过编码方式配置域名转发实现反向代理教程 10-10