java判断字符串是否是数字


正则表达式

    public static boolean isNum(String num){
    return  num.matches("(\\s)*([+-])?(([0-9]*\\.)?([0-9]+)|([0-9]+)(\\.[0-9]*)?)([eE][\\+-]?[0-9]+)?(\\s)*");
    }

利用BigDecimal的异常

  public static boolean isNum(String str){
        try {
            BigDecimal num = new BigDecimal(str);
        }catch (Exception e){//抛异常必定不是数字
            return false;
        }return true;
    }

判断字符是否是数字

Character.isDigit(ch)

判断字符是否是字母

boolean isLetter(char ch)

剑指offer题目:https://www.nowcoder.com/practice/6f8c901d091949a5837e24bb82a731f2?tpId=13&tqId=11206&tPage=3&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

import java.math.BigDecimal;
public class Solution {
    public boolean isNumeric(char[] str) {
        String num=new String(str);
        try{
           BigDecimal bd=new BigDecimal(num); 
        }catch(Exception e){
            return false;
        }
        return true;
        
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM