[英]Comparing two string and sorting them in alphabetical order
我想比较两个字符串并按字母顺序对它们进行排序。 我目前正在创建两个带有字符串的数组,并对它们进行排序,比较两个数组。
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中的所有基本数据类型类都实现了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);
}
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")
}
如果你只是寻找一个简单而优雅的代码而你不想预先优化,在java 8中你可以这样做:
String[] sorted = Stream.of(a, b).sorted().toArray(String[]::new);
System.out.println(sorted[0] + " is before " + sorted[1]);
这是问题的代码。
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.