现在的位置: 首页 > 综合 > 正文

[转]c#检查字符串是否为数字

2012年08月06日 ⁄ 综合 ⁄ 共 1121字 ⁄ 字号 评论关闭

c#检查字符串是否为数字

该日志由
samool
发表于 2007-12-28 10:01 AM

正则表达
   string regex = @^\d+$;

  自己写个方法吧:这是我写的.
          private bool isNumber(string s)
   {
    int Flag = 0;
    char[]str = s.ToCharArray();
    for(int i = 0;i < str.Length ;i++)
    {
     if (Char.IsNumber(str[i]))
    {
     Flag++;
    }
   else
   {
    Flag = -1;
    break;
   }
  }
  if ( Flag > 0 )
  {
   return true;
  }
  else
  {
   return false;
  }
          }

测试
                   private void Button1_Click(object sender, System.EventArgs e)
  {
   if (isNumber(TextBox1.Text.Trim()))
   {
    TextBox2.Text = 是数字;
   }
   else
   {
    TextBox2.Text = 不是数字;
   }
  }

 

try
{
 double.Parse(this.TextBox1.Text);
 Response.Write(是数字);
}
catch
{
 Response.Write(不是数字);
}

或者用正则表达式也可以:
using System.Text.RegularExpressions;
------------------------
Regex r=new Regex(@^\d+(\.)?\d*$);
if(r.IsMatch(this.TextBox1.Text))
{
 this.Response.Write(是数字);
}
else
{
 this.Response.Write(不是数字);
}

public static bool StrIsInt(string Str)
    {
      try
      {
        Int32.Parse(Str);
        return true;
      }
      catch
      {
        bool flag = false;
        return flag;
      }
    }

 

应该使用正则表达式:
string pattern = @^\d+(\.\d)?$;
if(Text1.Text.Trim()!=)
{
if(!Regex.IsMatch(sign_money.Text.Trim(),pattern))
{
   Text1不是数字;
}
else
{
  Text1是数字;
}
}

原文链接

抱歉!评论已关闭.