原文: https://beginnersbook.com/2018/10/java-program-to-sort-strings-in-an-alphabetical-order/

在这个 java 教程中,我们将学习如何按字母顺序对字符串进行排序。

Java 示例:按字母顺序排列字符串

在这个程序中,我们要求用户输入他想要输入的字符串计数以进行排序。一旦使用Scanner类捕获计数,我们已初始化输入计数大小的String数组,然后运行for循环以捕获用户输入的所有字符串。

一旦我们将所有字符串存储在字符串数组中,我们就会比较每个字符串的第一个字母,以便按字母顺序对它们进行排序。

  1. import java.util.Scanner;
  2. public class JavaExample
  3. {
  4. public static void main(String[] args)
  5. {
  6. int count;
  7. String temp;
  8. Scanner scan = new Scanner(System.in);
  9. //User will be asked to enter the count of strings
  10. System.out.print("Enter number of strings you would like to enter:");
  11. count = scan.nextInt();
  12. String str[] = new String[count];
  13. Scanner scan2 = new Scanner(System.in);
  14. //User is entering the strings and they are stored in an array
  15. System.out.println("Enter the Strings one by one:");
  16. for(int i = 0; i < count; i++)
  17. {
  18. str[i] = scan2.nextLine();
  19. }
  20. scan.close();
  21. scan2.close();
  22. //Sorting the strings
  23. for (int i = 0; i < count; i++)
  24. {
  25. for (int j = i + 1; j < count; j++) {
  26. if (str[i].compareTo(str[j])>0)
  27. {
  28. temp = str[i];
  29. str[i] = str[j];
  30. str[j] = temp;
  31. }
  32. }
  33. }
  34. //Displaying the strings after sorting them based on alphabetical order
  35. System.out.print("Strings in Sorted Order:");
  36. for (int i = 0; i <= count - 1; i++)
  37. {
  38. System.out.print(str[i] + ", ");
  39. }
  40. }
  41. }

输出:

Java 程序:按字母顺序排序字符串 - 图1

相关 Java 示例:

  1. Java 程序:在字符串中反转单词
  2. Java 程序:计算和打印学生成绩
  3. Java 程序:使用递归反转字符串
  4. Java 程序:查找字符串中的重复字符