zoukankan      html  css  js  c++  java
  • java中判断字符串是否是一个整数(转载)

    1.使用类型转换判断


      try { 
                    String str="123abc"; 
                    int num=Integer.valueOf(str);//把字符串强制转换为数字 
                    return true;//如果是数字,返回True 

        } 

        catch (Exception e) { 

                    return false;//如果抛出异常,返回False 
         }

     
    2.使用正则表达式判断


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

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


    4.使用Character.isDigit(char)判断


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

    来自: http://hi.baidu.com/frjay/blog/item/71b9500a685ee433b1351da8.html


  • 相关阅读:
    windows-如何免费让电脑自带的家庭中文版升级成专业版且不需要重装
    服务器管理-windows服务器如果让服务器自动定时重启
    International Olympiad In Informatics 2009 August 8 – 15, Plovdiv, Bulgaria Contest Day 1
    USACO 2008 FEB Eating Together
    POJ 2823 Sliding Window 滑动窗口 单调队列 Monotone Queue
    1st Junior Balkan Olympiad in Informatics Boats 船 DP
    USACO 2009 FEB Fair Shuttle 庙会班车 贪心
    USACO 2007 NOV Sunscreen 防晒霜 贪心
    JN 刷墙 过程DP
    Luogu
  • 原文地址:https://www.cnblogs.com/nature-zse/p/3604039.html
Copyright © 2011-2022 走看看