判斷C#中的字符串是否是數字,如果是轉換成int類型
1.通過正則表達式(可以判斷正數和負數)
a)
public int IsNumeric(string str)
{
int i;
if(str != null && System.Text.RegularExpressions.Regex.IsMatch(str,@"^-?/d+$"))
i = int.Parse(str);
else
i = -1;
return i;
}
b)
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);
}
c)
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*$");
}
2.通過字符
///
/// 判斷是否是數字
///
/// ///
private bool IsNumeric(string number)
{
try
{
for(int i=0;i {
if(number[i]<'0'||number[i]>'9')
{
return false;
}
}
return true;
}
catch
{
return false;
}
}
3.通過char.IsNumber方法
/// 判斷是否是數字
///
/// ///
private bool IsNumeric(string number)
{
try
{
for(int i=0;i {
if(!char.IsNumber(number,i))
{
return false;
}
}
return true;
}
catch
{
return false;
}
}
4.通過try,catch
/// 判斷是否是數字
///
/// ///
private bool IsNumeric(string number)
{
try
{
int.Parse(number);
return true;
}
catch
{
return false;
}
}
5.通過 ASCIIEncoding
///
/// 判斷是否是數字
///
/// 字符串 ///
public static bool IsNumeric(string str)
{
if (str == null || str.Length == 0 || str == string.Empty)
return false;
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
byte[] bytestr = ascii.GetBytes(str);
foreach (byte c in bytestr)
{
if (c < 48 || c > 57)
{
return false;
}
}
return true;
}
本文來源於yaosansi'Blog