Write a Java program to input a word and arrange its letters in alphabetical order and display the output.
Example-Input=APPLE
Output=AELPP
Also, you are not supposed to use the 'split' function.
Answers
Answer:
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] + ", ");
}
}
}
Answer:
import java.io.*;
public class Q14
{
public static void main(String[] a)throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String : ");
String ab=br.readLine();
char[] arr=ab.toCharArray();
int l=ab.length();
char temp;
for(int i=0;i<l-1;i++)
{
for(int j=0;j<l-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
String a1=String.valueOf(arr);
System.out.print("Sorted String: "+a1);
}
}
Answerd by M.Mithul Pranav
Hope it helps