Java Program to Sort a String


In this article, we will understand how to sort a string. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”). Strings are a sequence of characters

Below is a demonstration of the same −

Suppose our input is

Input string: javaprogram

The desired output would be

String after sorting is: [a, a, a, g, j, m, o, p, r, r, v]

Algorithm

Step 1 - START
Step 2 - Declare a string value namely input_string, a character array charArray, char value name temp and an int value namely string_size.
Step 3 - Define the values.
Step 4 - Assign the string to the character array.
Step 5 - Iterate over the elements of the character array twice, check if the adjacent elements are ordered, if not, swap them using temp variable.
Step 6 - Display the sorted array
Step 7 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.Arrays;
public class SortString {
   public static void main(String args[]) {
      int temp, string_size;
      String input_string = "javaprogram";
      System.out.println("The string is defined as: " +input_string);
      char charArray[] = input_string.toCharArray();
      string_size = charArray.length;
      for(int i = 0; i < string_size; i++ ) {
         for(int j = i+1; j < string_size; j++) {
            if(charArray[i]>charArray[j]) {
               temp = charArray[i];
               charArray[i] = charArray[j];
               charArray[j] = (char) temp;
            }
         }
      }
      System.out.println("\nThe characters of the string after sorting is: "+Arrays.toString(charArray));
   }
}

Output

The string is defined as: javaprogram

The characters of the string after sorting is: [a, a, a, g, j, m, o, p, r, r, v]

Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

import java.util.Arrays;
public class SortString {
   static void sort(String input_string){
      int temp, string_size;
      char charArray[] = input_string.toCharArray();
      string_size = charArray.length;
      for(int i = 0; i < string_size; i++ ) {
         for(int j = i+1; j < string_size; j++) {
            if(charArray[i]>charArray[j]) {
               temp = charArray[i];
               charArray[i] = charArray[j];
               charArray[j] = (char) temp;
            }
         }
      }
      System.out.println("\nThe characters of the string after sorting is: "+Arrays.toString(charArray));
   }
   public static void main(String args[]) {
      String input_string = "javaprogram";
      System.out.println("The string is defined as: " +input_string);
      sort(input_string);
   }
}

Output

The string is defined as: javaprogram

The characters of the string after sorting is: [a, a, a, g, j, m, o, p, r, r, v]

Updated on: 29-Mar-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements