在asp.net中驗證字元串是不是為數字我們沒有像php中那麼多豐富的函數來直接使用,這裡我整理了一些比較執行個體的驗證字元串是否為純數字方法代碼。
例1
代碼如下
複制代碼
#region 判斷是否為數字的方法
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;
#endregion
例2
class IsNumeric
{
//判斷字元串是否為純數字
public static bool IsNumber(string str)
{
if (str == null || str.Length == 0) //驗證這個參數是否為空
return false; //是,就傳回False
ASCIIEncoding ascii = new ASCIIEncoding();//new ASCIIEncoding 的執行個體
byte[] bytestr = ascii.GetBytes(str); //把string類型的參數儲存到數組裡
{
if (c < 48 || c > 57) //判斷是否為數字
{
return false; //不是,就傳回False
}
}
return true; //是,就傳回True
}
}
上面兩執行個體很簡單就是把字元類型擷取到然後再周遊判斷是不是數字即可。