首页 > 解决方案 > 如何在JAVA中比较包含整数的字符串

问题描述

我在比较包含整数的字符串时遇到了一些问题。像A11and A9orBA230BA7or之类的123东西9 我知道当我想比较整数(它们是字符串类型)时,我需要传递给 Integer 并进行比较,但事实并非如此。

它还包含字母和数字,所以我不能传入整数。

当我比较A11A9使用compareTo方法时,它说A9更大。当我与之相比123时,9它说9更大。

有没有人遇到过这个问题?请你帮助我好吗?谢谢。

标签: javaandroidstring

解决方案


/**
 * Similar to compareTo method But compareTo doesn't return correct result for string+integer strings something like `A11` and `A9`
  */

private int newCompareTo(String comp1, String comp2) {
    // If any value has 0 length it means other value is bigger
    if (comp1.length() == 0) {
        if (comp2.length() == 0) {
            return 0;
        }
        return -1;
    } else if (comp2.length() == 0) {
        return 1;
    }
    // Check if first string is digit
    if (TextUtils.isDigitsOnly(comp1)) {
        int val1 = Integer.parseInt(comp1);
        // Check if second string is digit
        if (TextUtils.isDigitsOnly(comp2)) { // If both strings are digits then we only need to use Integer compare method
            int val2 = Integer.parseInt(comp2);
            return Integer.compare(val1, val2);
        } else { // If only first string is digit we only need to use String compareTo method
            return comp1.compareTo(comp2);
        }

    } else { // If both strings are not digits

        int minVal = Math.min(comp1.length(), comp2.length()), sameCount = 0;

        // Loop through two strings and check how many strings are same
        for (int i = 0;i < minVal;i++) {
            char leftVal = comp1.charAt(i), rightVal = comp2.charAt(i);
            if (leftVal == rightVal) {
                sameCount++;
            } else {
                break;
            }
        }
        if (sameCount == 0) {
            // If there's no same letter, then use String compareTo method
            return comp1.compareTo(comp2);
        } else {
            // slice same string from both strings
            String newStr1 = comp1.substring(sameCount), newStr2 = comp2.substring(sameCount);
            if (TextUtils.isDigitsOnly(newStr1) && TextUtils.isDigitsOnly(newStr2)) { // If both sliced strings are digits then use Integer compare method
                return Integer.compare(Integer.parseInt(newStr1), Integer.parseInt(newStr2));
            } else { // If not, use String compareTo method
                return comp1.compareTo(comp2);
            }
        }
    }
}

推荐阅读