如何判断字符串是否存在数字

本文介绍了五种用于判断字符串是否为纯数字的方法:通过字符检查、使用VB.NET的IsNumeric函数、尝试转换为整数、使用try-catch块处理异常及正则表达式匹配。每种方法都有其适用场景和优缺点。
         //isDigit  
                public static bool isNumberic1(this string _string) 
                {
                    if (string.IsNullOrEmpty(_string))  
                        return false;        
                    foreach (char c in _string) 
                    {                 
                        if (!char.IsDigit(c))//if(c<'0' || c>'9')//最好的方法,在下面测试数据中再加一个0,然后这种方法效率会搞10毫秒左右   
                            return false;            
                    }           
                    return true;       
                }         
        //vb isnumberic     
        public static bool isNumberic2(this string _string)  
        {             
            return !string.IsNullOrEmpty(_string) && Microsoft.VisualBasic.Information.IsNumeric(_string);
        }         
        //try parese  
        public static bool isNumberic3(this string _string)  
        {             
            if (string.IsNullOrEmpty(_string)) 
                return false;    
            int i = 0;           
            return int.TryParse(_string, out i);   
        }       
        //try catch      
        public static bool isNumberic4(this string _string)   
        {            
            if (string.IsNullOrEmpty(_string))  
                return false;           
            try { int.Parse(_string); }    
            catch { return false; }    
            return true;         }     
        //regex        
        public static bool isNumberic5(this string _string)  
        {            
            return !string.IsNullOrEmpty(_string) && Regex.IsMatch(_string, "^\d+$");     
        }     

转载于:https://www.cnblogs.com/meiCode/p/3382498.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值