【问题标题】:Comparing two string and sorting them in alphabetical order比较两个字符串并按字母顺序排序
【发布时间】:2013-12-25 02:28:18
【问题描述】:

我想比较两个字符串并按字母顺序对它们进行排序。我目前正在使用字符串创建两个数组,并比较两个数组对它们进行排序。

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

这行得通,但它很费时间和内存。如果有人能提出更好的方法,我将不胜感激。

【问题讨论】:

  • 目标是什么?你能详细说明一下吗?

标签: java string sorting


【解决方案1】:

提示:java中的所有基本数据类型类都实现Comparable interface

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

【讨论】:

  • 如果你不是在普通的 ascii 模式下,这个策略是行不通的。见stackoverflow.com/a/12927962/2087666
  • 注意:大写字母的ASCII值小于小写字母的值。如果情况像 1> a="Ax" 和 b="aa" 或 2> a="aa" 和 b="AA"...结果将与预期的字母排序相矛盾。最好将两个字符串转换成一个共同的“CASE”,然后进行比较。
【解决方案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")
}

【讨论】:

  • 也添加一个相等的情况:)
  • 完成 - 也缓存了比较。
【解决方案3】:

如果您只是寻找简单而优雅的代码并且不想进行预优化,那么在 java 8 中您可以这样做:

String[] sorted = Stream.of(a, b).sorted().toArray(String[]::new);
System.out.println(sorted[0] + " is before " + sorted[1]);

【讨论】:

    【解决方案4】:

    这是问题的代码。

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

    【讨论】:

    • 请解释一下算法。
    猜你喜欢
    • 2022-01-02
    • 2012-04-29
    • 2013-10-22
    • 2018-05-17
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多