Warning: file_put_contents(/datas/wwwroot/jiajiahui/core/caches/caches_template/2/default/show.php): failed to open stream: Permission denied in /datas/wwwroot/jiajiahui/core/libraries/classes/template_cache.class.php on line 55

Warning: chmod(): Operation not permitted in /datas/wwwroot/jiajiahui/core/libraries/classes/template_cache.class.php on line 56
java中如何判断字符串是否为数字 - 源码之家

java中如何判断字符串是否为数字

java中如何判断字符串是否为数字?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

1、使用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
        }
    }
}

2、使用类型转换判断

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

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");  
}

关于java中如何判断字符串是否为数字问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。