zoukankan      html  css  js  c++  java
  • java判断一个字符串是否为数字型

    摘自:https://blog.csdn.net/qq_42133100/article/details/92158507

    方法一:用JAVA自带的函数(只能判断正整数 )

    1
    2
    3
    4
    5
    6
    7
    8
    2 public static boolean isNumeric(String str){
    3    for (int i = str.length();--i>=0;){ 
    4        if (!Character.isDigit(str.charAt(i))){
    5            return false;
    6        }
    7    }
    8    return true;
    9 }

      

    方法二:正则(推荐,速度最快)

    1
    2
    3
    4
    public static boolean isInteger(String str) { 
            Pattern pattern = Pattern.compile("^[-\+]?[\d]*$"); 
            return pattern.matcher(str).matches(); 
    }

      

    方法三:正则

    1
    2
    3
    4
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();  
    }

      

    方法四:正则

    1
    2
    3
    4
    5
    6
    public final static boolean isNumeric(String s) {
        if (s != null && !"".equals(s.trim()))
            return s.matches("^[0-9]*$");
        else
            return false;

      

    方法五:用ascii码 

    1
    2
    3
    4
    5
    6
    7
    8
    public static boolean isNumeric(String str){
        for(int i=str.length();--i>=0;){
            int chr=str.charAt(i);
            if(chr<48 || chr>57)
                return false;
        }
       return true;

      

    方法六:采用强制类转换来判断一个字符串是否为数字 (有局限性,如果要判断是int型或double型,就必须要调整转换语句,但可以判断正负)

    1
    2
    3
    4
    5
    6
    7
    8
    try 
            //Integer num = Integer.valueOf(str); 
            Double num2 = Double.valueOf(str); 
            //System.out.println("Is Number!" + num); 
            System.out.println("Is Number!" + num2); 
    catch (Exception e) { 
            System.out.println("Is not Number!"); 
    }

      

    方法七:采用正则表达式的方式来判断一个字符串是否为数字,这种方式判断面比较全面,可以判断正负、整数小数 (推荐)

    1
    2
    3
    4
    5
    6
    7
    //?:0或1个, *:0或多个, +:1或多个 
     Boolean strResult = str.matches("-?[0-9]+.?[0-9]*");    
     if(strResult == true) { 
                System.out.println("Is Number!"); 
            else 
                System.out.println("Is not Number!"); 
            }

      

  • 相关阅读:
    HTML <input> 标签
    HTML5 <input> type 属性
    静态页面与动态页面
    string::size_type 页73 size_t 页90
    template method(模板方法)
    C++中创建对象的时候加括号和不加括号的区别(转)
    _declspec(dllexport)和.def(转)
    智能指针
    C++中的delete加深认识
    工厂方法(整理自李建忠<C++设计模式>视频)
  • 原文地址:https://www.cnblogs.com/brithToSpring/p/13788119.html
Copyright © 2011-2022 走看看