Problem Statement: Given a String, Sort the characters in Ascending/Descending from a given String and return the String
Test Cases
Test Case – 1 | |
Input: | bushansirgur |
Output: | abghinrrssuu |
Test Case – 2 | |
Input: | bharathsirgur |
Output: | aabghhirrrstu |
Java Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class SortCharactersInWord { public static void main(String[] args) { System.out.println(sortCharacters("bushansirgur")); System.out.println(sortCharacters("bharathsirgur")); } public static String sortCharacters(String str){ char[] c = str.toCharArray(); for(int i = 0; i < c.length - 1; i++){ for(int j = i + 1; j < c.length; j++){ if(c[i] > c[j]){ char temp = c[i]; c[i] = c[j]; c[j] = temp; } } } return new String(c); } } |
Love this post?
Help me to buy a cup of coffee/Support us by donating.
All the donations will be go to the website maintenance/improvement.