按字母顺序对 Java 中的单词进行排序
这些单词按字母顺序或字典顺序进行排序。这意味着将根据单词中包含的字母按字母顺序对单词进行排序。以下给出了一个示例。
The original order of the words is Tom Anne Sally John The lexicographical order of the words is Anne John Sally Tom
展示这一点的程序如下。
示例
public class Example {
public static void main(String[] args) {
String[] words = { "Peach", "Orange", "Mango", "Cherry", "Apple" };
int n = 5;
System.out.println("The original order of the words is: ");
for(int i = 0; i < n; i++) {
System.out.println(words[i]);
}
for(int i = 0; i < n-1; ++i) {
for (int j = i + 1; j < n; ++j) {
if (words[i].compareTo(words[j]) > 0) {
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
System.out.println("
The lexicographical order of the words is: ");
for(int i = 0; i < n; i++) {
System.out.println(words[i]);
}
}
}输出
The original order of the words is: Peach Orange Mango Cherry Apple The lexicographical order of the words is: Apple Cherry Mango Orange Peach
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP