C#判断一个String是否为数字类型
方案一:Try...Catch(执行效率不高) 复制代码 代码如下: private bool IsNumberic(string oText)
{ try { int var1=Convert.ToInt32 (oText); return true; } catch { return false; } } 方案二:正则表达式(推荐) a) 复制代码 代码如下: public static bool IsNumeric(string value)
{ return Regex.IsMatch(value,@"^[+-]?/d*[.]?/d*$"); } public static bool IsInt(string value) { return Regex.IsMatch(value,@"^[+-]?/d*$"); } public static bool IsUnsign(string value) { return Regex.IsMatch(value,@"^/d*[.]?/d*$"); } b) 复制代码 代码如下: using System;
using System.Text.RegularExpressions; public bool IsNumber(String strNumber) return !objNotNumberPattern.IsMatch(strNumber) && 方案三:遍历 a) 复制代码 代码如下: public bool isnumeric(string str)
{ char[] ch=new char[str.Length]; ch=str.ToCharArray(); for(int i=0;i { if(ch[i]<48 || ch[i]>57) return false; } return true; } b) 复制代码 代码如下: public bool IsInteger(string strIn) {
bool bolResult=true; if(strIn=="") { bolResult=false; } else { foreach(char Char in strIn) { if(char.IsNumber(Char)) continue; else { bolResult=false; break; } } } return bolResult; } c) 复制代码 代码如下: public static bool isNumeric(string inString)
{ inString = inString.Trim(); bool haveNumber = false; bool haveDot = false; for (int i = 0; i < inString.Length; i++) { if (Char.IsNumber(inString[i])) { haveNumber = true; } else if (inString[i] == '.') { if (haveDot) { return false; } else { haveDot = true; } } else if (i == 0) { if (inString[i] != '+' && inString[i] != '-') { return false; } } else { return false; } if (i > 20) { return false; } } return haveNumber; } 方案四:改写vb的IsNumeric源代码(执行效率不高) 复制代码 代码如下: //主调函数
public static bool IsNumeric(object Expression) { bool flag1; IConvertible convertible1 = null; if (Expression is IConvertible) { convertible1 = (IConvertible) Expression; } if (convertible1 == null) { if (Expression is char[]) { Expression = new string((char[]) Expression); } else { return false; } } TypeCode code1 = convertible1.GetTypeCode(); if ((code1 != TypeCode.String) && (code1 != TypeCode.Char)) { return Utils.IsNumericTypeCode(code1); } string text1 = convertible1.ToString(null); try { long num2; if (!StringType.IsHexOrOctValue(text1,ref num2)) { double num1; return DoubleType.TryParse(text1,ref num1); } flag1 = true; } catch (Exception) { flag1 = false; } return flag1; }//子函数 // return Utils.IsNumericTypeCode(code1); internal static bool IsNumericTypeCode(TypeCode TypCode) { switch (TypCode) { case TypeCode.Boolean: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: { return true; } case TypeCode.Char: case TypeCode.SByte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: { break; } } return false; } //----------------- 方案五:直接引用vb运行库(执行效率不高) 方法:首先需要添加Visualbasic.runtime的引用 以上就是C#判断一个String是否为数字类型的全部内容,推荐大家使用正则表达式的方法,比较简单且效率高。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |