Java 比较两个字符串并按字母顺序对它们进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20445900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:58:59  来源:igfitidea点击:

Comparing two string and sorting them in alphabetical order

javastringsorting

提问by

I want to compare two strings and sort them in alphabetical order. I am currently creating two arrays with the strings and sorting one them comparing the two arrays.

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

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

This works but it is time and memory consuming. I would appreciate if anyone can suggest a better way to do this.

这有效,但它是时间和内存消耗。如果有人能提出更好的方法来做到这一点,我将不胜感激。

采纳答案by Amit Sharma

Hint: All basic data type classes in java implement Comparable interface.

提示: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);
}

回答by irla

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

回答by Anton Ivinskyi

If you just look for an easy and elegant code and you do not want to preoptimize, in java 8 you can do like this:

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

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

回答by Siva Sankaran

Here is the code for the problem.

这是问题的代码。

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