网站大量收购独家精品文档,联系QQ:2885784924

.net 判断是否为数字.doc

  1. 1、本文档共6页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
.net 判断是否为数字

.net 判断是否为数字 在编程的时候,经常遇到要判断一个字符串中的字符是否全部是数字(0-9),本来是一个很容易实现的功能,但程序员首先会想到的是,这样简单的功能有没有现成的函数可以用呢?VB.NET中有个IsNumeric(object),C#中只有判断单个字符的Char.IsNumber(),IsNumeric可以判断double类型的数字字符串,但无法排除正负号和小数点,如果判断字符串是否是一个数的话用它挺合适,但不能用来判断字符串是否全部由数字组成的。没现成的方法了,只好自己写函数: public static bool IsNum(String str) { for(int i=0;istr.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 = int start, end; int i; string toBeTested = 6741s; #region Test user function start = System.Environment.TickCount; for(i=0; itimes; 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; itimes; i++) { isNumeric.IsMatch(toBeTested); } end = System.Environment.TickCount; Console.WriteLine(Regular Expression Time: + (end-start)/1000.0 + Seconds); #endregion #region Test Exception start = System.Environment.TickCount; for(i=0; itimes/100; i++) { try { Int32.Parse(toBeTested); } catch { //发生了异常,那么就不是数字了。 } } end = System.Environment.TickCount; Console.WriteLine(Exception Time: + (end-start)/10.0 + Seconds); #endregion #region Test VB.NET IsNumeric() start = System.Environment.TickCount; for(i=0; itimes/10; i++) { Microsoft.VisualBasic.Information.IsNumeric(toBeTested); } end = System.Environment.TickCount; Console.WriteLine(VB.NET IsNumeric() Time: + (end-start)/100.0 + Seconds); #endregion 因为Exception所用的时间太长,所以只测试了1/100,这样不太严谨,但是数量级不会错的。 三次运行的结果是: User function Time: 1.938 Seconds Regular Expression Time: 11.921 Seconds Exception Time: 600 Seconds VB.NET IsNumeric() Time: 40.797 Seconds User function Time: 1.953 Seconds Regular Expression Time: 12.016 Seconds Exception Time: 590.6 Seconds VB

文档评论(0)

jgx3536 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

版权声明书
用户编号:6111134150000003

1亿VIP精品文档

相关文档