Java Program to Sort Characters of a String
Sorting a String's characters is one of the most asked Interview Questions in Java. Today let's see how this can be solved in a really easy manner.
We will be utilizing an inbuilt java function in Java.Utils library -> Arrays.sort()
We need to import Java.utils in order to use it.
import java.util.*;
A string is nothing but an array of characters. The function that we are going to use also needs an char array as an input. So, we'll be converting the String into a character array.
//Load the string into a character array. char[] temp = a.toCharArray();
Now we'll use the Arrays.sort function to do the heavy work of sorting for us.
//Sort the Array Arrays.sort(temp);
Let's combine all this information together for a working code.
You can copy paste this code into a new .java file and see it working for yourself!
package coding; import java.util.*; public class Practice { public static void main(String[] args) { //Create an object of the class Practice practice = new Practice(); //call the sort function practice.sortString("ilikecomputengine"); } /** * Function to sort the characters of a String * @author computengine.com * @param a */ public void sortString(String a) { System.out.println("Received String:"+a); //Load the string into a character array. char[] temp = a.toCharArray(); //Sort the Array Arrays.sort(temp); System.out.println("Sorted String:"+String.valueOf(temp)); } }
And here is the output of this code :
Received String: ilikecomputengine
Sorted String: ceeegiiiklmnnoptu
Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on Facebook, Twitter, Tumblr.
Comments
Post a Comment