Java Program to Sort Strings in an Alphabetical Order

Veröffentlicht am: 25 Mai 2021
auf dem Kanal: Aman Tripathi
471
6

INSTAGRAM |   / javac_programming  
In this program, we are asking user to enter the count of strings that he would like to enter for sorting. Once the count is captured using Scanner class, we have initialized a String array of the input count size and then are running a for loop to capture all the strings input by user.

Once we have all the strings stored in the string array, we are comparing the first alphabet of each string to get them sorted in the alphabetical order.

import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int count;
String temp;
Scanner scan = new Scanner(System.in);

//User will be asked to enter the count of strings
System.out.print("Enter number of strings you would like to enter:");
count = scan.nextInt();


String str[] = new String[count];
Scanner scan2 = new Scanner(System.in);

//User is entering the strings and they are stored in an array
System.out.println("Enter the Strings one by one:");
for(int i = 0; i _ count; i++)
{
str[i] = scan2.nextLine();
}
scan.close();
scan2.close();

//Sorting the strings
for (int i = 0; i _ count; i++)
{
for (int j = i + 1; j _ count; j++) {
if (str[i].compareTo(str[j])_0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}

//Displaying the strings after sorting them based on alphabetical order
System.out.print("Strings in Sorted Order:");
for (int i = 0; i _= count - 1; i++)
{
System.out.print(str[i] + ", ");
}
}
}


Auf dieser Seite können Sie das Online-Video Java Program to Sort Strings in an Alphabetical Order mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Aman Tripathi 25 Mai 2021 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 471 Mal angesehen und es wurde von 6 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!