欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#判断一个String是否为数字类型

程序员文章站 2022-05-28 18:43:33
方案一:try...catch(执行效率不高) 复制代码 代码如下:private bool isnumberic(string otext) {  &nb...

方案一:try...catch(执行效率不高)

复制代码 代码如下:
private bool isnumberic(string otext)
{
    try
    {
        int var1=convert.toint32 (otext);
        return true;
    }
    catch
    {
        return false;
    }
}

方案二:正则表达式(推荐)

a)

复制代码 代码如下:
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*$");
}

b)

复制代码 代码如下:
using system;
using system.text.regularexpressions;

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);
}

方案三:遍历

a)

复制代码 代码如下:
public bool isnumeric(string str)
{
    char[] ch=new char[str.length];
    ch=str.tochararray();
    for(int i=0;i    {
        if(ch[i]<48 || ch[i]>57)
            return false;
    }
    return true;
}

b)

复制代码 代码如下:
public bool isinteger(string strin) {
    bool bolresult=true;
    if(strin=="") {
        bolresult=false;
    }
    else {
        foreach(char char in strin) {
            if(char.isnumber(char))
                continue;
            else {
                bolresult=false;
                break;
            }
        }
    }
    return bolresult;
}

c)

复制代码 代码如下:
public static bool isnumeric(string instring)
{
    instring = instring.trim();
    bool havenumber = false;
    bool havedot = false;
    for (int i = 0; i < instring.length; i++)
    {
        if (char.isnumber(instring[i]))
        {
            havenumber = true;
        }
        else if (instring[i] == '.')
        {
            if (havedot)
            {
                return false;
            }
            else
            {
                havedot = true;
            }
        }
        else if (i == 0)
        {
            if (instring[i] != '+' && instring[i] != '-')
            {
                return false;
            }
        }
        else
        {
            return false;
        }
        if (i > 20)
        {
            return false;
        }
    }
    return havenumber;
}

方案四:改写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");

以上就是c#判断一个string是否为数字类型的全部内容,推荐大家使用正则表达式的方法,比较简单且效率高。