在这里,我们将解释如何编写一个 Java 程序来按字母顺序排序字符串。首先,我们需要将用户想要排序的字符串数量读入一个变量。然后,我们需要将这些字符串读入一个数组。通过使用 for 循环,我们可以比较字符串并将它们放置到正确的位置。
我们可以使用 compareTo() 方法在 Java 中比较字符串。下面是 compareTo() 的一个示例。
StringA.compareTo(StringB) 其中 StringA 和 StringB 是字符串。
如果两个字符串相等,compareTo() 函数返回零。如果 StringA 大于 StringB,则该函数返回一个正值。
如果 StringA 小于 StringB,则该函数返回一个负值。
首先,我们必须声明具有公共修饰符的类 Sortstr。然后打开 main() 函数。然后将用户想要输入的字符串数量读入变量 n。使用 for 循环将字符串读入数组 str[i]。然后使用嵌套的 for 循环,将 str[i] 与 str[j] 进行比较。如果 str[i] 大于 str[j],则交换位置。之后,使用 for 循环显示数组 str[] 中的元素。
步骤 1:声明具有公共修饰符的类 Sortstr。
步骤 2:打开 main() 以启动程序,Java 程序执行从 main() 开始
步骤 3:声明变量 n 为整数,t 为字符串。
步骤 4:将字符串数量读入变量 n。
步骤 5:声明大小为 n 的字符串数组 str[]。
步骤 6:使用条件为 i 的 for 循环
步骤 7:使用条件为 j 的另一个 for 循环
步骤 8:比较字符串 str[i] 与 str[j]。如果为真,则交换 str[i] 与 str[j]。
步骤 9:将 j 递增一并执行步骤 7。
步骤 10:使用 for 循环将 str[i] 中的元素显示为已排序的字符串。
import java.util.Scanner;
public class SortStr
{
public static void main(String[] args)
{
int n;
String t;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of strings:");
n= sc.nextInt();
String str[] = new String[n];
Scanner sc1 = new Scanner(System.in);
System.out.println("Enter the Strings :");
for(int i = 0; i < n; i++)
{
str[i] = sc1.nextLine();
}
sc.close();
sc1.close();
//sort the strings
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++) {
if (str[i].compareTo(str[j])>0)
{
t = str[i];
str[i] = str[j];
str[j] = t;
}
}
}
System.out.print("Sorted strings:");
for (int i = 0; i <= n- 1; i++)
{
System.out.println(str[i]);
}
}
}
Enter number of strings:4 Enter the Strings : Zayan Abi Biju Rini Sorted Strings: Abi Biju Rini Zayan