• C#判断一个string是否为数字


    案一:Try...Catch(执行效率不高)
    private bool IsNumberic(string oText)
    {
              try
             {
                      int var1=Convert.ToInt32 (oText);
                      return true;
             }
              catch
             {
                      return false;
             }
    }
    
     
    
    方案二:正则表达式(推荐)
    using System.Text.RegularExpressions; 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*$"); } public static bool isTel(string strInput) { return Regex.IsMatch(strInput, @"d{3}-d{8}|d{4}-d{7}"); } 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 { 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; }
  • 相关阅读:
    php使用cookie来保存用户登录信息
    Linux下进程操作
    TortoiseSVN无法编辑日志信息的解决方法
    用DIV布局制作公告板
    HashMap的遍历
    实现文本滚动
    子DIV块中设置margintop时影响父DIV块位置的解决办法
    php使用session来保存用户登录信息
    javascript jquery ajax动态提交多个参数 api测试 拂晓风起
    javascript 处理返回json中的\u中文乱码问题(也不是乱码了,就是\u编码) 拂晓风起
  • 原文地址:https://www.cnblogs.com/hailexuexi/p/5351654.html
Copyright © 2020-2023  润新知