Sorting comma-separated numbers in a string in Java
Hello Tech Aspirants, I hope you are doing well.
In this tutorial, we will solve a sorting problem in a quite different way.
The problem says that we will be provided by a comma-separated string and we have to sort that string in ascending order.
Example of Sorting comma-Separated number
The above figure shows the explanation of Sorting comma-separated numbers in a String. In this diagram, we have an input string which is [1,2,-3,4,100] including some white spaces.
We have to sort these numbers ignoring blank spaces in ascending order.
Some constraints are taken while solving this algorithm
- The String may contain any number of white spaces.
- We have to ignore white spaces, such that it doesn’t play any role in sorting.
- Store the comma-separated integers in an array.
- Perform sort the separated integers in ascending order.
Java Code for the above explanation:-
- Take a comma-separated input consisting spaces.
- Split the string separated by ‘,’ by split function and store it in an array (x).
- Take a loop from 0 to the length of the array (x)
Remove all the white spaces from the array(x) and store it in an array(z). - Take any kind of sorting to sort the array (z).
- Print the sorted array.
import java.util. Scanner; class sort_comma_string { public static void main(String args[]) { Scanner sc=new Scanner(System.in); String a; a=sc.nextLine(); int l=a.length(); int z[]=new int[l]; String x[]=new String[l]; x=a.split(","); for(int j=0;j<x.length;j++) { x[j]=x[j].replaceAll("\\s",""); int y=Integer.parseInt(x[j]); z[j]=y; } for(int i=0;i<x.length-1;i++) { for(int k1=i+1;k1<x.length;k1++) { if(z[i]>z[k1]) { int temp=z[i]; z[i]=z[k1]; z[k1]=temp; } } } for(int i=0;i<x.length;i++) { System.out.println(z[i]); } } }
As the output result, we will get what you can see below:
1, 2, -3,4, 100 -3 1 2 4 100
Hope this tutorial helped you.
Also, read: Converting Java Array to JSON?
Leave a Reply