简体   繁体   English

查看字符串是否包含所有数字的方法

[英]Method to see if string contains ALL digits

I need to complete the method allDigits using isDigit that i wrote, that when passed a valid String, returns true if all characters of the String are digits, and false otherwise. 我需要使用我编写的isDigit完成方法allDigits,即当传递有效字符串时,如果字符串的所有字符均为数字,则返回true,否则返回false。

So far i have: 到目前为止,我有:

public static boolean isDigit (char ch){
    if (ch >= '0' && ch <= '9')
        return true;
    return false;
}

public static boolean allDigits(String s){
    for (int i =0; i<s.length(); i++)
        if(isDigit(s.charAt(i)) == true)
            return true;
    return false;
}

But this returns true if just say 但这只是说说而返回true

public static void main(String[] args) {
    String s = "abc123";
    System.out.println(allDigits(s));
}

OUTPUT: true 输出:真

However should return false 但是应该返回false

ALSO: Is my code efficient? 还:我的代码有效吗? I feel like theres an easier way. 我觉得有一种更简单的方法。 Any help is appreciated thanks 任何帮助表示赞赏,谢谢

You should check each character and if it be not numeric, then return false, otherwise return true: 您应该检查每个字符,如果不是数字,则返回false,否则返回true:

public static boolean allDigits(String s) {
    for (int i=0; i < s.length(); i++) {
        if (!isDigit(s.charAt(i)))
            return false;
    }

    return true;
}

But a cleaner way to handle this, and what I would do is to use a regex: 但是,更干净的方法可以解决此问题,而我要做的就是使用正则表达式:

public static boolean allDigits(String s) {
    return s.replaceAll("\\d", "").equals("");
}

Note that the above method will treat an empty string as having all numeric characters. 请注意,上述方法会将空字符串视为具有所有数字字符。 If you want empty string to fail, it would be easy to add this logic as an edge case. 如果您希望空字符串失败,则可以很容易地将此​​逻辑添加为边缘情况。

I would always look for an already existing solution. 我将始终寻找现有的解决方案。 How about using https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringUtils.html#isNumeric(java.lang.CharSequence) ? 如何使用https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringUtils.html#isNumeric(java.lang.CharSequence)呢?

I have confidence in these open source solutions concerning efficiency and correctness. 我对这些涉及效率和正确性的开源解决方案充满信心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM