分享
 
 
 

C#判斷一個string是否可以爲數字的幾種解決方案

來源:互聯網網民  2008-12-13 08:24:25  
窄屏简体版  字體: ||  

方案一:Try...Catch(執行效率不高)view plaincopy to clipboardprint?

/// <summary>

/// 名稱:IsNumberic

/// 功能:判斷輸入的是否是數字

/// 參數:string oText:源文本

/// 返回值:bool true:是false:否

/// </summary>

/// <param name="oText"></param>

/// <returns></returns>

private bool IsNumberic(string oText)

{

try

{

int var1=Convert.ToInt32 (oText);

return true;

}

catch

{

return false;

}

}

/// <summary>

/// 名稱:IsNumberic

/// 功能:判斷輸入的是否是數字

/// 參數:string oText:源文本

/// 返回值:bool true:是false:否

/// </summary>

/// <param name="oText"></param>

/// <returns></returns>

private bool IsNumberic(string oText)

{

try

{

int var1=Convert.ToInt32 (oText);

return true;

}

catch

{

return false;

}

}方案二:正則表達式(推薦)

a)view plaincopy to clipboardprint?

using System;

using System.Text.RegularExpressions;

public bool IsNumber(String strNumber)

{

Regex objNotNumberPattern=new Regex("[^0-9.-]");

Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*");

Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*");

String strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";

String strValidIntegerPattern="^([-]|[0-9])[0-9]*$";

Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")");

return !objNotNumberPattern.IsMatch(strNumber) &&

!objTwoDotPattern.IsMatch(strNumber) &&

!objTwoMinusPattern.IsMatch(strNumber) &&

objNumberPattern.IsMatch(strNumber);

}

using System;

using System.Text.RegularExpressions;

public bool IsNumber(String strNumber)

{

Regex objNotNumberPattern=new Regex("[^0-9.-]");

Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*");

Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*");

String strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";

String strValidIntegerPattern="^([-]|[0-9])[0-9]*$";

Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")");

return !objNotNumberPattern.IsMatch(strNumber) &&

!objTwoDotPattern.IsMatch(strNumber) &&

!objTwoMinusPattern.IsMatch(strNumber) &&

objNumberPattern.IsMatch(strNumber);

}b)view plaincopy to clipboardprint?

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*$");

}

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*$");

}方案三:遍曆 www.devdao.com

a)view plaincopy to clipboardprint?

public bool isnumeric(string str)

{

char[] ch=new char[str.Length];

ch=str.ToCharArray();

for(int i=0;i<ch.Length;i++)

{

if(ch[i]<48 || ch[i]>57)

return false;

}

return true;

}

public bool isnumeric(string str)

{

char[] ch=new char[str.Length];

ch=str.ToCharArray();

for(int i=0;i<ch.Length;i++)

{

if(ch[i]<48 || ch[i]>57)

return false;

}

return true;

}b)view plaincopy to clipboardprint?

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;

}

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)view plaincopy to clipboardprint?

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;

}

}

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源代碼(執行效率不高)view plaincopy to clipboardprint?

//主調函數

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;

}

//-----------------

//StringType.IsHexOrOctValue(text1, ref num2))

internal static bool IsHexOrOctValue(string Value, ref long i64Value)

{

int num1;

int num2 = Value.Length;

while (num1 < num2)

{

char ch1 = Value[num1];

if (ch1 == '&')

{

ch1 = char.ToLower(Value[num1 + 1], CultureInfo.InvariantCulture);

string text1 = StringType.ToHalfwidthNumbers(Value.Substring(num1 + 2));

if (ch1 == 'h')

{

i64Value = Convert.ToInt64(text1, 0x10);

}

else if (ch1 == 'o')

{

i64Value = Convert.ToInt64(text1, 8);

}

else

{

throw new FormatException();

}

return true;

}

if ((ch1 != ' ') && (ch1 != '\u3000'))

{

return false;

}

num1++;

}

return false;

}

//----------------------------------------------------

// DoubleType.TryParse(text1, ref num1);

internal static bool TryParse(string Value, ref double Result)

{

bool flag1;

CultureInfo info1 = Utils.GetCultureInfo();

NumberFormatInfo info3 = info1.NumberFormat;

NumberFormatInfo info2 = DecimalType.GetNormalizedNumberFormat(info3);

Value = StringType.ToHalfwidthNumbers(Value, info1);

if (info3 == info2)

{

return double.TryParse(Value, NumberStyles.Any, info2, out Result);

}

try

{

Result = double.Parse(Value, NumberStyles.Any, info2);

flag1 = true;

}

catch (FormatException)

{

flag1 = double.TryParse(Value, NumberStyles.Any, info3, out Result);

}

catch (Exception)

{

flag1 = false;

}

return flag1;

}

//主調函數

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;

}

//-----------------

//StringType.IsHexOrOctValue(text1, ref num2))

internal static bool IsHexOrOctValue(string Value, ref long i64Value)

{

int num1;

int num2 = Value.Length;

while (num1 < num2)

{

char ch1 = Value[num1];

if (ch1 == '&')

{

ch1 = char.ToLower(Value[num1 + 1], CultureInfo.InvariantCulture);

string text1 = StringType.ToHalfwidthNumbers(Value.Substring(num1 + 2));

if (ch1 == 'h')

{

i64Value = Convert.ToInt64(text1, 0x10);

}

else if (ch1 == 'o')

{

i64Value = Convert.ToInt64(text1, 8);

}

else

{

throw new FormatException();

}

return true;

}

if ((ch1 != ' ') && (ch1 != '\u3000'))

{

return false;

}

num1++;

}

return false;

}

//----------------------------------------------------

// DoubleType.TryParse(text1, ref num1);

internal static bool TryParse(string Value, ref double Result)

{

bool flag1;

CultureInfo info1 = Utils.GetCultureInfo();

NumberFormatInfo info3 = info1.NumberFormat;

NumberFormatInfo info2 = DecimalType.GetNormalizedNumberFormat(info3);

Value = StringType.ToHalfwidthNumbers(Value, info1);

if (info3 == info2)

{

return double.TryParse(Value, NumberStyles.Any, info2, out Result);

}

try

{

Result = double.Parse(Value, NumberStyles.Any, info2);

flag1 = true;

}

catch (FormatException)

{

flag1 = double.TryParse(Value, NumberStyles.Any, info3, out Result);

}

catch (Exception)

{

flag1 = false;

}

return flag1;

}方案五: 直接引用vb運行庫(執行效率不高)

方法: 首先需要添加Visualbasic.runtime的引用

代碼中Using Microsoft.visualbasic;

程序中用Information.isnumeric("ddddd");

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
方案一:Try...Catch(執行效率不高)view plaincopy to clipboardprint? /// <summary> /// 名稱:IsNumberic /// 功能:判斷輸入的是否是數字 /// 參數:string oText:源文本 /// 返回值: bool true:是 false:否 /// </summary> /// <param name="oText"></param> /// <returns></returns> private bool IsNumberic(string oText) { try { int var1=Convert.ToInt32 (oText); return true; } catch { return false; } } /// <summary> /// 名稱:IsNumberic /// 功能:判斷輸入的是否是數字 /// 參數:string oText:源文本 /// 返回值: bool true:是 false:否 /// </summary> /// <param name="oText"></param> /// <returns></returns> private bool IsNumberic(string oText) { try { int var1=Convert.ToInt32 (oText); return true; } catch { return false; } }方案二:正則表達式(推薦) a)view plaincopy to clipboardprint? using System; using System.Text.RegularExpressions; public bool IsNumber(String strNumber) { Regex objNotNumberPattern=new Regex("[^0-9.-]"); Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*"); Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*"); String strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$"; String strValidIntegerPattern="^([-]|[0-9])[0-9]*$"; Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")"); return !objNotNumberPattern.IsMatch(strNumber) && !objTwoDotPattern.IsMatch(strNumber) && !objTwoMinusPattern.IsMatch(strNumber) && objNumberPattern.IsMatch(strNumber); } using System; using System.Text.RegularExpressions; public bool IsNumber(String strNumber) { Regex objNotNumberPattern=new Regex("[^0-9.-]"); Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*"); Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*"); String strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$"; String strValidIntegerPattern="^([-]|[0-9])[0-9]*$"; Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")"); return !objNotNumberPattern.IsMatch(strNumber) && !objTwoDotPattern.IsMatch(strNumber) && !objTwoMinusPattern.IsMatch(strNumber) && objNumberPattern.IsMatch(strNumber); }b)view plaincopy to clipboardprint? 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*$"); } 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*$"); }方案三:遍曆 [url=http://www.devdao.com]www.devdao.com[/url] a)view plaincopy to clipboardprint? public bool isnumeric(string str) { char[] ch=new char[str.Length]; ch=str.ToCharArray(); for(int i=0;i<ch.Length;i++) { if(ch[i]<48 || ch[i]>57) return false; } return true; } public bool isnumeric(string str) { char[] ch=new char[str.Length]; ch=str.ToCharArray(); for(int i=0;i<ch.Length;i++) { if(ch[i]<48 || ch[i]>57) return false; } return true; }b)view plaincopy to clipboardprint? 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; } 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)view plaincopy to clipboardprint? 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; } } 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源代碼(執行效率不高)view plaincopy to clipboardprint? //主調函數 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; } //----------------- //StringType.IsHexOrOctValue(text1, ref num2)) internal static bool IsHexOrOctValue(string Value, ref long i64Value) { int num1; int num2 = Value.Length; while (num1 < num2) { char ch1 = Value[num1]; if (ch1 == '&') { ch1 = char.ToLower(Value[num1 + 1], CultureInfo.InvariantCulture); string text1 = StringType.ToHalfwidthNumbers(Value.Substring(num1 + 2)); if (ch1 == 'h') { i64Value = Convert.ToInt64(text1, 0x10); } else if (ch1 == 'o') { i64Value = Convert.ToInt64(text1, 8); } else { throw new FormatException(); } return true; } if ((ch1 != ' ') && (ch1 != '\u3000')) { return false; } num1++; } return false; } //---------------------------------------------------- // DoubleType.TryParse(text1, ref num1); internal static bool TryParse(string Value, ref double Result) { bool flag1; CultureInfo info1 = Utils.GetCultureInfo(); NumberFormatInfo info3 = info1.NumberFormat; NumberFormatInfo info2 = DecimalType.GetNormalizedNumberFormat(info3); Value = StringType.ToHalfwidthNumbers(Value, info1); if (info3 == info2) { return double.TryParse(Value, NumberStyles.Any, info2, out Result); } try { Result = double.Parse(Value, NumberStyles.Any, info2); flag1 = true; } catch (FormatException) { flag1 = double.TryParse(Value, NumberStyles.Any, info3, out Result); } catch (Exception) { flag1 = false; } return flag1; } //主調函數 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; } //----------------- //StringType.IsHexOrOctValue(text1, ref num2)) internal static bool IsHexOrOctValue(string Value, ref long i64Value) { int num1; int num2 = Value.Length; while (num1 < num2) { char ch1 = Value[num1]; if (ch1 == '&') { ch1 = char.ToLower(Value[num1 + 1], CultureInfo.InvariantCulture); string text1 = StringType.ToHalfwidthNumbers(Value.Substring(num1 + 2)); if (ch1 == 'h') { i64Value = Convert.ToInt64(text1, 0x10); } else if (ch1 == 'o') { i64Value = Convert.ToInt64(text1, 8); } else { throw new FormatException(); } return true; } if ((ch1 != ' ') && (ch1 != '\u3000')) { return false; } num1++; } return false; } //---------------------------------------------------- // DoubleType.TryParse(text1, ref num1); internal static bool TryParse(string Value, ref double Result) { bool flag1; CultureInfo info1 = Utils.GetCultureInfo(); NumberFormatInfo info3 = info1.NumberFormat; NumberFormatInfo info2 = DecimalType.GetNormalizedNumberFormat(info3); Value = StringType.ToHalfwidthNumbers(Value, info1); if (info3 == info2) { return double.TryParse(Value, NumberStyles.Any, info2, out Result); } try { Result = double.Parse(Value, NumberStyles.Any, info2); flag1 = true; } catch (FormatException) { flag1 = double.TryParse(Value, NumberStyles.Any, info3, out Result); } catch (Exception) { flag1 = false; } return flag1; }方案五: 直接引用vb運行庫(執行效率不高) 方法: 首先需要添加Visualbasic.runtime的引用 代碼中Using Microsoft.visualbasic; 程序中用Information.isnumeric("ddddd");
󰈣󰈤
 
 
 
>>返回首頁<<
 
 
 
 
 熱帖排行
 
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有