Follow @devglan
Java Program to Find Duplicate Character from a String and Count of repetition
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"); } }
Explanation
Click to Suggest Your Own Explanation
As we know, HashMap implementation in java holds key value pair and it does not provide duplicate keys, here in the program we have used hashmap to hold the different character of a string and whenver a key already exists in the map simply increase the count of the hashmap value.At the end we can get the duplicate character whose hashmap value is greater then 1 along with the repeated count of the character.
Other Similar Java Programs:
If You Appreciate This, You Can Consider:
- Share this article on social media or with your teammates.