Sorting Characters Alphabetically Ignoring Case Sensitive: This Java program transforms an input string into a new format following specific rules. The goal of the program is to create a new string in which each character from the input string is repeated exactly twice, once in uppercase and once in lowercase, and they appear in sorted order based on their lowercase representation.
Sorting Characters Alphabetically Ignoring Case Sensitive
package com.softwaretestingo.interviewprograms; import java.util.Set; import java.util.TreeMap; public class InterviewPrograms17 { /* * Input string: "AcBCbDEdea" * Output string:"AaBbCcDdEe" */ public static void main(String[] args) { TreeMap<Character,Integer> map1 = new TreeMap<Character,Integer>(); String S1="AcBCbDEdea"; System.out.println("Given Initial String: "+S1); char[] array = S1.toLowerCase().toCharArray(); for(char c:array) { if(map1.containsKey(c)) { map1.put(c,map1.get(c)+1); } else { map1.put(c,1); } } Set<Character> set=map1.keySet(); System.out.print("The String Gets Transformed to the Below Format: "); for(Character character:set) { if(map1.get(character)==2) { System.out.print(Character.toUpperCase(character)+""+Character.toLowerCase(character)); } } } }
Output:
Given Initial String: AcBCbDEdea The String Gets Transformed to the Below Format: AaBbCcDdEe
Here’s how the program achieves this:
Import Statements: The program imports the necessary classes from the java.util package, specifically Set and TreeMap, to use sets and sorted maps.
main Method: The program defines the main method where the execution starts.
Initialization: A TreeMap named map1 is created with characters as keys and their frequency (number of occurrences) as values. The input string S1 is defined as “AcBCbDEdea”.
Counting Characters: The program converts the input string to lowercase using toLowerCase() and then converts it into a character array. It then iterates through each character in the array and updates the map1 TreeMap to count the occurrences of each character.
Transforming and Printing: After counting the occurrences, the program retrieves the key set from map1, which contains the unique characters in the input string. It then iterates through the characters in the key set. For each character, if its frequency in map1 is 2, it means the character appeared twice, so the program prints the character once in uppercase and once in lowercase.
For the given input string “AcBCbDEdea”, the output will be “AaBbCcDdEe”, which represents the transformed string that fulfills the specified requirements.
Leave a Reply