In this article, we will discuss steps and execution program to uppercase all duplicate characters/occurrences from given String
Uppercase duplicate character in String :
Steps:
- Initially, create empty StringBuilder object to store all converted string
- first, LOWER-CASE entire original String before any operation
- create String[] array using space (\\s) as delimiter in split(); method of String
- Iterate through original String after split (Outer for-loop)
- while iterating, store split’ed string in temporary variable
- create LinkedHashSet to check/store duplicate occurrences
- convert temp String into character-array (char[]) using toCharArray(); method
- Iterate through converted char[] array (Inner for-each loop)
- check whether char already present in LinkedHashSet, while iterating Inner for-loop
- If not present, then add to LinkedHashSet using add(); method as well as StringBuilder using append(); method
- If present, then store duplicate character in StringBuilder after converting to UPPER-CASE
- add single space to StringBuilder after each iteration of Outer for-loop
- finally pretty print to console
UpperCaseDuplicateCharacterInString.java
package in.bench.resources.collection; import java.util.LinkedHashSet; import java.util.Set; public class UpperCaseDuplicateCharacterInString { public static void main(String[] args) { // sample test string String testStr = "madam sss gg fff rr malayalam"; Set<Character> lhSet = null; // Step 1: create StringBuilder object // to store converted strings StringBuilder sbuilder = new StringBuilder(); // Step 2: first, LOWER-CASE entire String before any operation String lowerStr = testStr.toLowerCase(); // Step 3: create String[] using // space as delimiter in split() method of String String[] strArray = lowerStr.split("\\s"); // Step 4: Iterate original String after split for(int index=0; index < strArray.length; index++) { // Step 5: store it in temporary variable String temp = strArray[index]; // Step 6: create LinkedHashSet to check/store duplicate lhSet = new LinkedHashSet<Character>(); // Step 7: convert temp String into character-array // using toCharArray() method char[] chArray = temp.toCharArray(); // Step 8: iterate through converted char[] array for(char ch : chArray) { // Step 9: check whether char already present in LHSet boolean checkChar = lhSet.contains(ch); // Step 10: if not present, then add if(!checkChar) { lhSet.add(ch); sbuilder.append(ch); } else { // Step 11: if present, then store duplicate // after converting to UPPER-CASE in StringBuilder sbuilder.append(Character.toUpperCase(ch)); } } // Step 12: add single space after outer for-loop sbuilder.append(" "); } // Step 13: finally pretty print to console System.out.println("Original String : " + testStr); System.out.println("\nConverted String : " + sbuilder.toString().trim()); } }
Output :
Original String : madam sss gg fff rr malayalam Converted String : madAM sSS gG fFF rR malAyALAM
Happy Coding !!
Happy Learning !!