import java.util.HashMap; import java.util.Map; public class FindDuplicateChar { public static void countDuplicate(String str){ /*Create a Map to store each Character with their count */ Map<Character, Integer> charMap = new HashMap<Character, Integer>(); /* Get Character array from String */ char[] charArray = str.toCharArray(); /*Iterate over Char Array and populate map*/ for(Character ch:charArray){ if(charMap.containsKey(ch)){ charMap.put(ch, charMap.get(ch)+1); } else { charMap.put(ch, 1); } } /* Print Character with their count */ for (Map.Entry entry:charMap.entrySet()) { System.out.println(entry.getKey()+" = "+entry.getValue()); } } public static void main(String a[]){ FindDuplicateChar obj = new FindDuplicateChar(); String text = "ABCDABCDEFGHIJKLABCD"; System.out.println("Text -"+text); FindDuplicateChar.countDuplicate(text); } }
Monday, 31 August 2020
Java code to find duplicate Characters in a String
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment