C#验证输入的是否数字的几种方法

来源:互联网 发布:日本道教 知乎 编辑:程序博客网 时间:2024/05/22 14:07

static bool IsNumeric(string str)            //方法一
  { 
       if (str==null || str.Length==0)
          return false;
       foreach(char c in str)
       {
           if (!Char.IsNumber(c))
           {
              return false;
           }
       }
       return true;
  } 

private bool IsNumeric(string s)          //方法二
{
    char ch0 = '0';
    char ch9 = '9';
    for(int i=0; i < s.Length; i++)
    {
        if ((s[i] < ch0 || s[i] > ch9))
        {
            return false;
        }
    }
    return true;
}

static bool IsNumeric (string str)            //方法三-----------使用正则表达式
{  
   System.Text.RegularExpressions.Regex reg1 
       = new System.Text.RegularExpressions.Regex(@"^[-]?/d+[.]?/d*$"); 
   return reg1.IsMatch(str);
}