How to easily sort characters in a String?

Often companies like Google or Microsoft ask you simple questions like sorting an array during your interview. This is the easiest way I have found to sort the string:

  1. Convert the String to characters array using someString.toCharArray();
  2. Then use Arrays.sort() to sort the character array
  3. Finally create a new String with the sorted characters array

Here is the code and it’s output:

package com.icodejava.blog.datastructure;

import java.util.Arrays;

/**
 * @author Kushal Paudyal 
 * www.icodejava.com 
 * Created On - Feb 14, 2014 
 * Last Modified On - Feb 14, 2014
 */
public class StringSort {
	public static void main(String args[]) {
		System.out.println(sort("Please Sort Me"));
	}

	/**
	 * @param string - String to be sorted
	 * @return sorted string
	 */
	private static String sort(String string) {
		if (string == null) {
			return null;
		}

		char[] characters = string.toCharArray();
		Arrays.sort(characters);
		return new String(characters);

	}

}

Output:

MPSaeeelorst

  1. Implementing a Simple LIFO Stack in Java using LinkedList
  2. Implementing a Simple FIFO Queue in Java Using Linked List
  3. Protected: Behavioral Questions – Interview
  4. In Place Matrix (2D Array) Clockwise and Counterclockwise Rotation – Java Implementation
  5. Matrix (2D Array) Clockwise and Counterclockwise Rotation with Extra Buffer – Java Implementation
  6. Array Max Integer Finder (With Big O Analysis)
  7. A Basic Implementation of Binary Tree in Java
  8. A Basic Implementation of Generic Tree in Java
  9. Basic example of implementing Singly Linked List in Java
  10. Top XML Interview Questions
  11. J2EE Interview Questions
  12. Webservice Interview Questions
  13. Core Java Interview Preparation Questions
  14. How to Add and Remove nodes in an unsorted Linked List
  15. Rotating a two dimensional integer array In-Place and using extra memory
  16. How to reverse a Singly Linked List iteratively and recursively
  17. Sorted Circular Linked List Implementation And Insert Operation
  18. Finding Mean Value Of An Integer Array In Java
  19. How to intersect two sets in Java using java.util.Set data structure.
  20. Bubble Sorting An Integer Array In Ascending and Descending Order
  21. How to split strings and separate the words with spaces
  22. Finding if two Strings are Anagrams
  23. How to easily sort characters in a String?
Tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *