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 FacebookTwitterTumblr.

Comments

Popular posts from this blog

Calculate Your CTC Salary Hike Percentage - Online Calculator to find your New Salary

Find the Longest Streak of 1's in a Binary Array using Java Code

Java Program to read Excel File and Load into Array

Java Program to Read a Properties file and return a Property Value

Create a File logging Utility using Java Code