PROGRAM 16 : ENTER A STRING AND ARRANGE THE CHARACTERS IN ALPHABETICAL ORDER,REMOVING ALL SPACES OF THE STRING.
Example:
Example:
PROGRAM :
import java.util.Scanner;
public class alphabeticalorder
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
String str = sc.nextLine();
str = str.toUpperCase();
int l = str.length();
int i , j;
char arr[] = new char[l]; // creating 'char' array to store the characters of string
for(i = 0 ; i<l ; i++)
arr[i] = str.charAt(i);// METHOD IS USED TO EXTRACT THE CHARACTERS OF STRING
char t; // TEMPORARY VARIABLE CREATED
for(i = 0 ; i<l ; i++) // SORTING OF CHARACTERS IN ASCENDING ORDER BY USING BUBBLE SORTING TECHNIQUE
{
for(j = 0 ; j<l-i-1 ; j++)
{
if(arr[j]>arr[j+1]) // COMPARING THE ELEMENTS OF ARRAY
{
t = arr[j]; // SWAPPING MECHANISM
arr[j] = arr[j+1];
arr[j+1] = t;
}
}
}
String s = ""; //CREATE A NEW STRING TO REMOVE THE SPACES
for(i = 0 ; i<l ; i++)
s+=arr[i];
s = s.trim(); // USING trim() method for eliminating the extra spaces
System.out.println("OUTPUT:");
System.out.println(s);
}
}
public class alphabeticalorder
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
String str = sc.nextLine();
str = str.toUpperCase();
int l = str.length();
int i , j;
char arr[] = new char[l]; // creating 'char' array to store the characters of string
for(i = 0 ; i<l ; i++)
arr[i] = str.charAt(i);// METHOD IS USED TO EXTRACT THE CHARACTERS OF STRING
char t; // TEMPORARY VARIABLE CREATED
for(i = 0 ; i<l ; i++) // SORTING OF CHARACTERS IN ASCENDING ORDER BY USING BUBBLE SORTING TECHNIQUE
{
for(j = 0 ; j<l-i-1 ; j++)
{
if(arr[j]>arr[j+1]) // COMPARING THE ELEMENTS OF ARRAY
{
t = arr[j]; // SWAPPING MECHANISM
arr[j] = arr[j+1];
arr[j+1] = t;
}
}
}
String s = ""; //CREATE A NEW STRING TO REMOVE THE SPACES
for(i = 0 ; i<l ; i++)
s+=arr[i];
s = s.trim(); // USING trim() method for eliminating the extra spaces
System.out.println("OUTPUT:");
System.out.println(s);
}
}
No comments:
Post a Comment