比较字符串

时间:2017-04-18 13:04:25

标签: java

我希望比较使用字符和数字比较字符串比较的方法

假设我有2个字符串: s1 =" abc 123" 和字符串 s2 =" abc 45a" 使用时比较java的方法我有结果s2> s1,但我想要一个返回s1>的比较方法s2(因为123> 45)。

另一个例子 s3 =" def45" s4 =" abc100" 我想要比较方法返回s3> s4因为d>一种 java有这样的内置方法吗?

2 个答案:

答案 0 :(得分:1)

您可以这样做:

 private Integer extcartNumberFromString(String str) {
    return Integer.parseInt(str.replaceAll("[^0-9]", ""));
  }

实施例

String s = "abc125";
String c = "abc12";
Integer a= extcartNumberFromString(s); // 125
Integer b = extcartNumberFromString(c); //12
System.out.println(a.compareTo(b)); // 1 because a > b

答案 1 :(得分:1)

这是一个想法:

public class MyStringComparator implements Comparator<String> {
    @override
    public int compare(String a, String b) {
        // replace digits by ""
        String aLetters = a.replaceAll("\d", "");
        String bLetters = b.replaceAll("\d", "");

        int diff = aLetters.compareTo(bLetters);
        if (diff != 0) {
            return diff;
        }

        // diff == 0 means, that strings are equal

        // replace non-digits by ""
        String aDigits = a.replaceAll("\D", "");
        String bDigits = b.replaceAll("\D", "");

        int aNumber = Integer.parseInt(aDigits);
        int bNumber = Integer.parseInt(bDigits);

        return aNumber - bNumber;
    }
}

现在,使用MyStringComparator

public static void main(String[] args) {
    MyStringComparator c = new MyStringComparator();
    displayResult(c, "abc 123", "abc 45a");
    displayResult(c, "def45", "abc100");
} 

public static void displayResult(MyStringComparator c, String s1, String s2) {
    int result = c.compare(s1, s2);
    if (result < 0) {
       System.out.println("s1 < s2");
    }
    if (result > 0) {
       System.out.println("s1 > s2");
    }
    if (result == 0) {
       System.out.println("s1 = s2");
    } 
}