首页 > 开发 > 综合 > 正文

[总结]C#判断一个string是否可以为数字,五种解决方案!

2020-02-03 13:45:07
字体:
来源:转载
供稿:网友

最大的网站源码资源下载站,

方案一:try...catch(执行效率不高)
/// <summary>
/// 名称:isnumberic
/// 功能:判断输入的是否是数字
/// 参数:string otext:源文本
/// 返回值: bool true:是 false:否
/// </summary>
/// <param name="otext"></param>
/// <returns></returns>
private bool isnumberic(string otext)
{
try
         {
int var1=convert.toint32 (otext);
return true;
         }
catch
{
return false;
}
}

方案二:正则表达式(推荐)
a)
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);
}

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*$");
}
方案三:遍历
a)
public bool isnumeric(string str)
{
    char[] ch=new char[str.length];
    ch=str.tochararray();
    for(int i=0;i<ch.length;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");

 

 


trackback: http://tb.blog.csdn.net/trackback.aspx?postid=292673

[点击此处收藏本文]   发表于 2005年02月18日 3:53 pm

 


sam 发表于2005-02-19 10:07 pm  ip: 218.70.110.*
看来第一种办法最有简单。


冰戈 发表于2005-02-20 9:26 am  ip: 220.163.28.*
第一种办法效率不高,建议不用


ofei 发表于2005-03-12 5:43 pm  ip: 219.137.251.*
第二种和第三种方法都没有判断数值范围
用"99999999999999999999"作为参数 判断isinteger()再用int.pase()的话定会出错
用"9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"作为参数 判断isnumber() 再用double.parse()的话也肯定出错

 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表