按字母顺序打印带有字母标题的列表
Printing a list in alphabetical order with letter headings
我有一个按字母顺序排列的字符串列表我想打印,但我想打印相应的字母标题。例如:
["Blue","Cat in hat","Zebra","2 Words"]
## B
Blue
## C
Cat in hat
## Z
Zebra
## [0-9]
2 Words
最好的方法是什么?它应该不区分大小写,所以 "hello" 和 "Hello" 都在 H.
下
这对你有帮助:
注意:假设列表是sorted.Otherwise你需要先做排序。
for (String str : stringList) {
if (Character.isDigit(str.charAt(0))) {
if (!Character.isDigit(previousChar)) {
System.out.println("## [0-9]");
}
} else if (Character.toUpperCase(str.charAt(0)) != previousChar) {
System.out.println("## " + Character.toUpperCase(str.charAt(0)));
}
previousChar = Character.toUpperCase(str.charAt(0));
System.out.println(str);
}
我有一个按字母顺序排列的字符串列表我想打印,但我想打印相应的字母标题。例如:
["Blue","Cat in hat","Zebra","2 Words"]
## B
Blue
## C
Cat in hat
## Z
Zebra
## [0-9]
2 Words
最好的方法是什么?它应该不区分大小写,所以 "hello" 和 "Hello" 都在 H.
下这对你有帮助:
注意:假设列表是sorted.Otherwise你需要先做排序。
for (String str : stringList) {
if (Character.isDigit(str.charAt(0))) {
if (!Character.isDigit(previousChar)) {
System.out.println("## [0-9]");
}
} else if (Character.toUpperCase(str.charAt(0)) != previousChar) {
System.out.println("## " + Character.toUpperCase(str.charAt(0)));
}
previousChar = Character.toUpperCase(str.charAt(0));
System.out.println(str);
}