Sort Characters in a String in Java
Sorting characters in a string means arranging all characters in a specific order (usually ascending order based on ASCII values).
This program helps understand character comparison, loops, and basic sorting logic without relying on library methods.
Understanding the Problem
Given a string, we need to:
- Convert the string into a character array.
- Compare characters using their ASCII values.
- Sort them in ascending order.
Example 1
Input: programming
Output: aggimmnoprr
Example 2
Input: Java
Output: Jaa v → (ASCII sorted) → Jaav
Logic Explanation
- Convert the string to a character array.
- Use two nested loops to compare characters.
- Swap characters if they are in the wrong order.
- Continue until all characters are sorted.
Java Program to Sort Characters in a String
import java.util.Scanner;
public class SortCharacters {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length - 1; i++) {
for (int j = i + 1; j < ch.length; j++) {
if (ch[i] > ch[j]) {
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
}
}
}
System.out.print("Sorted string: ");
for (char c : ch) {
System.out.print(c);
}
}
}
Sample Output
Enter a string: programming
Sorted string: aggimmnoprr
Important Notes
- Sorting is based on ASCII values.
- Uppercase letters appear before lowercase letters.
- Spaces and special characters are also sorted if present.
Practice Challenges
- Modify the program to sort characters in descending order.
- Ignore spaces while sorting characters.
- Sort characters without converting to a character array.
This program builds a strong foundation in string manipulation and sorting algorithms in Java.