Write a program in Java to display the words of a string in alphabetical order from A to Z.
import java.util.Scanner;
public class AtoZ {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String line;
System.out.println("Enter the string:");
line=sc.nextLine();
System.out.println("Entered string is:"+line);
//split the entered string which contains the space between the words- (" ")
String[] words = line.split(" ");
String temp;
// swap the words according to alphabetical order
for(int i=0;i<words.length;i++){
for(int j=i+1;j<words.length;j++){
if(words[i].compareTo(words[j])>0){
temp=words[i];
words[i]=words[j];
words[j]=temp;
}
}
}
System.out.print("The required string in the alphabetical order:");
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
}
}
Comments
Leave a comment