Given a string, write a program to re-arrange all the numbers appearing in the string in decreasing order. Note: There will not be any negative numbers or numbers with decimal part.
Answers
Program in Java:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner Sc = new Scanner(System.in);
System.out.print("Enter a sentence : ");
String S = Sc.nextLine();
String A[] = S.split(" ");
int l = A.length;
int N[] = new int[l];
int c = 0;
for(int i = 0; i < l; i++)
{
try
{
int x = Integer.parseInt(A[i]);
N[c] = x;
c++;
}
catch(Exception e)
{
continue;
}
}
for(int i = 0; i < c; i++)
{
for(int j = 0; j < c-1-i; j++)
{
if(N[j] < N[j+1])
{
int temp = N[j];
N[j] = N[j+1];
N[j+1] = temp;
}
}
}
String new_string = "";
c = 0;
for(int i = 0; i < l; i++)
{
try
{
int x = Integer.parseInt(A[i]);
new_string = new_string + N[c]+ " ";
c++;
}
catch(Exception e)
{
new_string = new_string + A[i] + " ";
}
}
System.out.print(new_string);
}
}
Output:
Enter a sentence : I have 12 apples, 24 bananas and 6 mangoes.
I have 24 apples, 12 bananas and 6 mangoes.