我在这里: 首页 » 程序人生 » 浏览文章: 在C#里面判断一个String是否为数字
« SQL 2005 建立数据库图表时出现以下错误Database diagram support objects cannot be installed because this database does not have a valid owner 解决办法.新成语【正龙拍虎】 »

在C#里面判断一个String是否为数字

有时候为了判断一个字符串是否为数字,不是数字的怎么处理,比如在程序中传id进行查询等。大致有以下几种做法:

一、进行try catch异常处理(效率低)
        示例:
         private bool IsNumberic(string oText)
        {
          try
         {
                  int var1=Convert.ToInt32 (oText);
                  return true;
         }
          catch
         {
                  return false;
         }
     }

二、正则表达式判断(注意添加引用 System.Text.RegularExpressions)
        示例:
         a)
    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);
    }

    b)
    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*$");
    }

三、遍历
        示例:
       public bool isnumeric(string str)
       {
                char[] ch=new char[str.Length];
                ch=str.ToCharArray();
                for(int i=0; i< str.Length; i++)
                {
                        if(ch[i]<48 || ch[i]>57)
                        return false;
                 }
                return true;
         }
      
四、改写vb的IsNumeric源代码 (-_-!)
        示例:
       //主调函数
       public static bool IsNumeric(object Expression)
       {
      bool flag1;
      IConvertible convertible1 = null;
      if (Expression is IConvertible)
      {
            convertible1 = (IConvertible) Expression;
      }
      if (convertible1 == null)
      {
            if (Expression is char[])
            {
                  Expression = new string((char[]) Expression);
            }
            else
            {
                  return false;
            }
      }
      TypeCode code1 = convertible1.GetTypeCode();
      if ((code1 != TypeCode.String) && (code1 != TypeCode.Char))
      {
            return Utils.IsNumericTypeCode(code1);
      }
      string text1 = convertible1.ToString(null);
      try
      {
            long num2;
            if (!StringType.IsHexOrOctValue(text1, ref num2))
            {
                  double num1;
                  return DoubleType.TryParse(text1, ref num1);
            }
            flag1 = true;
      }
      catch (Exception)
      {
            flag1 = false;
      }
      return flag1;
       }
      //子函数
       // return Utils.IsNumericTypeCode(code1);
       internal static bool IsNumericTypeCode(TypeCode TypCode)
       {
      switch (TypCode)
      {
            case TypeCode.Boolean:
            case TypeCode.Byte:
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
            case TypeCode.Single:
            case TypeCode.Double:
            case TypeCode.Decimal:
            {
                  return true;
            }
            case TypeCode.Char:
            case TypeCode.SByte:
            case TypeCode.UInt16:
            case TypeCode.UInt32:
            case TypeCode.UInt64:
            {
                  break;
            }
      }
      return false;
       }
 

       //-----------------
       //StringType.IsHexOrOctValue(text1, ref num2))
       internal static bool IsHexOrOctValue(string Value, ref long i64Value)
       {
      int num1;
      int num2 = Value.Length;
      while (num1 < num2)
      {
            char ch1 = Value[num1];
            if (ch1 == '&')
            {
                  ch1 = char.ToLower(Value[num1 + 1], CultureInfo.InvariantCulture);
                  string text1 = StringType.ToHalfwidthNumbers(Value.Substring(num1 + 2));
                  if (ch1 == 'h')
                  {
                        i64Value = Convert.ToInt64(text1, 0x10);
                  }
                  else if (ch1 == 'o')
                  {
                        i64Value = Convert.ToInt64(text1, 8);
                  }
                  else
                  {
                        throw new FormatException();
                  }
                  return true;
            }
            if ((ch1 != ' ') && (ch1 != '\u3000'))
            {
                  return false;
            }
            num1++;
      }
      return false;
       }
       //----------------------------------------------------
       // DoubleType.TryParse(text1, ref num1);
       internal static bool TryParse(string Value, ref double Result)
       {
      bool flag1;
      CultureInfo info1 = Utils.GetCultureInfo();
      NumberFormatInfo info3 = info1.NumberFormat;
      NumberFormatInfo info2 = DecimalType.GetNormalizedNumberFormat(info3);
      Value = StringType.ToHalfwidthNumbers(Value, info1);
      if (info3 == info2)
      {
            return double.TryParse(Value, NumberStyles.Any, info2, out Result);
      }
      try
      {
            Result = double.Parse(Value, NumberStyles.Any, info2);
            flag1 = true;
      }
      catch (FormatException)
      {
            flag1 = double.TryParse(Value, NumberStyles.Any, info3, out Result);
      }
      catch (Exception)
      {
            flag1 = false;
      }
      return flag1;
       }

五、直接引用vb运行库(效率低)
    添加Visualbasic.runtime的引用
    代码中Using Microsoft.visualbasic;
    程序中用Information.isnumeric("ddddd");

[部分代码来自网络搜集未经调试, 通不过的...别怪我]

发表评论

为了防止SPAM,含链接的评论需要审核后才能显示。

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

日历

支持我们

最新评论及回复

最近发表

搜索