java中判断字符串是否是一个整数

转自:http://blog.sina.com.cn/s/blog_6e9c16890100na5q.html

1.使用类型转换判断

    try { 
                 String str="123abc"; 
                int num=Integer.valueOf(str);//把字符串强制转换为数字 
                return true;//如果是数字,返回True 
             } catch (Exception e) { 
                return false;//如果抛出异常,返回False 
            }

2.使用正则表达式判断

    String str = "abc123"; 
    boolean isNum = str.matches("[0-9]+"); 
    //+表示1个或多个(如"3"或"225"),*表示0个或多个([0-9]*)(如""或"1"或"22"),?表示0个或1个([0-9]?)(如""或"7")

3.使用Pattern类和Matcher

         String str = "123"; 
             Pattern pattern = Pattern.compile("[0-9]+"); 
             Matcher matcher = pattern.matcher((CharSequence) str); 
            boolean result = matcher.matches(); 
            if (result) { 
                 System.out.println("true"); 
             } else { 
                 System.out.println("false"); 
            }

4.使用Character.isDigit(char)判断
    String str = "123abc"; 
      if (!"".equals(str)) { 
       char num[] = str.toCharArray();//把字符串转换为字符数组 
        StringBuffer title = new StringBuffer();//使用StringBuffer类,把非数字放到title中 
        StringBuffer hire = new StringBuffer();//把数字放到hire中 
    
       for (int i = 0; i < num.length; i++) { 
    
      // 判断输入的数字是否为数字还是字符 
     if (Character.isDigit(num[i])) {把字符串转换为字符,再调用Character.isDigit(char)方法判断是否是数字,是返回True,否则False 
          hire.append(num[i]);// 如果输入的是数字,把它赋给hire 
      } else { 
       title.append(num[i]);// 如果输入的是字符,把它赋给title 
      } 
     } 
    }


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值