Description
While dealing with string, many of the time it is required to find or remove duplicate character from a string.Following is the java program to find duplicate or repeated characters from a given string.The program also results the cont of the duplicate characters.
package com.devglan; import java.util.HashMap; import java.util.Map; import java.util.Set; public class DuplicateChar { public void findDuplicateCharsInString(String str){ Mapmap = new HashMap (); char[] chars = str.toCharArray(); for(Character ch : chars){ if(map.containsKey(ch)){ map.put(ch, map.get(ch)+1); } else { map.put(ch, 1); } } Set keys = map.keySet(); for(Character ch : keys){ if(map.get(ch) > 1){ System.out.println(ch + " -- " + map.get(ch)); } } } public static void main(String a[]){ DuplicateChar duplicateChar = new DuplicateChar(); duplicateChar.findDuplicateCharsInString("india"); } }