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是数字;
}
}

 傻猫网络日志标签:    .net, 字符串, 数字
网摘: Yahoo Baidu Google Bolaa 365Key Yesky Wozhai POCO ViVi YouNote Hexun Del.icio.us Yeeyoo igooi I2Key Cn3 Bytemen Furl Blinklist Blogmarks Technorati 分享到饭否
相关文章: (最多只显示5条记录)
2008短信最流行之数字传情 (浏览:2610, 评论:0)
IsNumeric 判断字符串是否为数字 (浏览:2054, 评论:0)
VB6如何访问.NET WebService服务 (浏览:1730, 评论:0)
Delphi函数返回多个值 (浏览:2422, 评论:0)
Working with .NET data in Delphi (浏览:3344, 评论:0)
发表评论:( 来了就留个脚印吧!你的参与是我最大的动力!)

    

(单击图片换张图片)