比较两个字符串并按字母顺序排序

8

我想比较两个字符串并按字母顺序排序。目前我正在创建两个包含这些字符串的数组,并通过比较这两个数组来对其中一个进行排序。

String a="LetterA";
String b="ALetterB";
String[] array1={a.toLowerCase(),b.toLowerCase()};
String[] array2={a.toLowerCase(),b.toLowerCase()};
Arrays.sort(array2);
if (Arrays.equals(array1, array2)){
    System.out.println(a+" is before "+b);
}
else{
    System.out.println(b+" is before "+a);
}

这种方法可以实现,但它会消耗大量时间和内存。如果有人能够提出更好的方法来完成这个任务,我将不胜感激。


1
什么是目标?你能详细说明一下吗? - Amit Sharma
4个回答

23

提示:Java中所有基本数据类型的类都实现了Comparable接口

String a="LetterA";
String b="ALetterB";
int compare = a.compareTo(b);
if (compare < 0){
    System.out.println(a+" is before "+b);
}
else if (compare > 0) {
    System.out.println(b+" is before "+a);
}
else {
    System.out.println(b+" is same as "+a);
}

2
如果您不在纯ASCII模式下,此策略将无法正常工作。请参见https://dev59.com/xmcs5IYBdhLWcg3wWClB#12927962。 - Remi Morin
注意:大写字母的ASCII值小于小写字母。如果情况如下:1> a="Ax",b="aa" 或者 2> a="aa",b="AA" ... 结果将与预期的字母顺序相矛盾。最好将两个字符串都转换为相同的“CASE”,然后再进行比较。 - Deepeshkumar

2
int compare = a.compareTo(b);
if (compare < 0){
    System.out.println(a + " is before " +b);
} else if (compare > 0) {
    System.out.println(b + " is before " +a);
} else {
    System.out.println("Strings are equal")
}

也加上相等的情况 :) - Amit Sharma
完成 - 同时缓存比较。 - irla

1
如果您只是寻找一种简单而优雅的代码,并且不想进行预优化,在Java 8中,您可以像这样做:
String[] sorted = Stream.of(a, b).sorted().toArray(String[]::new);
System.out.println(sorted[0] + " is before " + sorted[1]);

0

这是问题的代码。

 public static void main(String[] args) {
    String a="Angram";
    String b="Angram";

    if(a.length()==b.length()) {
        char c[]=a.toCharArray();
        char d[]=b.toCharArray();
        Arrays.sort(c);
        Arrays.sort(d);
        a=new String(c);
        b=new String(d);
        if(a.equals(b)) 
            System.out.print("Yes");
        else
            System.out.print("No");
    }
    else {
        System.out.print("No");
    }
}

请解释算法。 - Avishek Bhattacharya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接