按字母顺序重新排序字符串变量
问题描述:
嘿所以我想知道什么是按字母顺序重新排序3个不同字符串变量的有效方法?我试图使用.compareTo()作为比较它们的一种方式。但是如果将这个转换回重新排序的字符串列表,我们陷入了困惑和困惑之中。按字母顺序重新排序字符串变量
public static void main(String args[])
{
String a = "Can", b = "Am", c = "Be", d= " ";
int first = a.compareTo(b);
int second = a.compareTo(c);
int third = b.compareTo(c);
int fourth = d.compareTo(d);
if (first > 0)
{
fourth = second;
second = first;
first = fourth;
}
System.out.println(first);
System.out.println(second);
System.out.println(third);
System.out.println(fourth);
}
答
您可以将它们放到TreeSet中。 TreeSet按字母顺序自动为您订购。
示例代码:
String a = "Can", b = "Am", c = "Be", d= " ";
TreeSet<String> set=new TreeSet<>()
set.add(a);
set.add(b);
set.add(c);
set.add(d);
for (String s:set){
System.out.println(s);
}
答
一种简单的方法来做到这一点是将字符串存储在数组中,然后对其进行排序
String[] array= {"Can", "Am", "Be", " "};
Arrays.sort(array);
for (String string : array) {
System.out.println(string);
}
答
使用Collections.sort()方法如下
List<String> arr = new ArrayList<>();
arr.add("Can");
arr.add("Am");
arr.add("Be");
arr.add(" ");
System.out.println("Before sort : "+arr);
Collections.sort(arr);
System.out.println("After sort : "+arr);
输出:
Before sort : [Can, Am, Be, ]
After sort : [ , Am, Be, Can]
是否有任何理由你使用多个变量,而不仅仅是一个数组或列表,它可以很容易地排序? –
将它们全部放在字符串列表中,然后调用'List.sort()'(来自Java 8)或'Collections.sort()' –