How to Sort a String in Java alphabetically in Java?

JavaObject Oriented ProgrammingProgramming

Using the toCharArray() method

The toCharArray() method of this class converts the String to a character array and returns it. To sort a string value alphabetically −

  • Get the required string.

  • Convert the given string to a character array using the toCharArray() method.

  • Sort the obtained array using the sort() method of the Arrays class.

  • Convert the sorted array to String by passing it to the constructor of the String array.

Example

 Live Demo

import java.util.Arrays;
import java.util.Scanner;
public class SortingString {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string value: ");
      String str = sc.nextLine();
      char charArray[] = str.toCharArray();
      Arrays.sort(charArray);
      System.out.println(new String(charArray));
   }
}

Output

Enter a string value:
Tutorialspoint
Taiilnooprsttu

Sorting the array manually

To sort the array manually −

  • Get the required string.

  • Convert the given string to a character array using the toCharArray() method.

  • Compare the first two elements of the array.

  • If the first element is greater than the second swap them.

  • Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them.

  • Repeat this till the end of the array.

Example

 Live Demo

import java.util.Arrays;
import java.util.Scanner;
public class SortingString {
   public static void main(String args[]) {
      int temp, size;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string value: ");
      String str = sc.nextLine();
      char charArray[] = str.toCharArray();
      size = charArray.length;
      for(int i = 0; i < size; i++ ) {
         for(int j = i+1; j < size; j++) {
            if(charArray[i]>charArray[j]) {
               temp = charArray[i];
               charArray[i] = charArray[j];
               charArray[j] = (char) temp;
            }
         }
      }
      System.out.println("Third largest element is: "+Arrays.toString(charArray));
   }
}

Output

Enter a string value:
Tutorialspoint
Third largest element is: [T, a, i, i, l, n, o, o, p, r, s, t, t, u]
raja
Published on 14-Oct-2019 12:34:50
Advertisements