Java Program To Find Duplicate Characters In a String
- June 15, 2020
- by
In this Java Program, we find the duplicate characters in a string by using HashMap.
HashMap is made up of keys and values. In our program we are going to insert chars into keys and their counts into values and get the set of duplicate keys in the string.
Logic: char are inserted as keys and their count as values
Step 1 : Import java.util.HashMap, java.util.Map, java.util.Set
Step 2 : Create class DupCharacters
Step 3 : Create a HashMap
Step 4 : Convert the string to char array
Step 5 : Apply the logic and if map contains the char already then increase the value by 1
Step 6 : Apply the for loop
Step 7 : Obtain the set of keys
Step 8 : Display count of chars if it is greater than 1
Step 9 : Apply for loop
Step 10 : Create the main method
Step 11 : Create the object of the DupCharacters class and display the result by using System.out.print method.
Program :
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
class DupCharacters
{
public void countDupChars(String str)
{
//Create a HashMap
Map<Character, Integer> map = new HashMap<Character, Integer>();
//Convert the string to char array
char[] chars = str.toCharArray();
//logic: char are inserted as keys and their count as values
//If map contains the char already then increase the value by 1
for(Character ch:chars)
{
if(map.containsKey(ch))
{
map.put(ch, map.get(ch)+1);
}
else
{
map.put(ch,1);
}
}
//Obtaining set of keys
Set<Character> keys = map.keySet();
//Display count of chars if it is greater than 1
//All duplicate chars would be having value greater than 1
for(Character ch:keys)
{
if(map.get(ch)>1)
{
System.out.println("Char"+ch+""+map.get(ch));
}
}
}
public static void main(String[] args)
{
DupCharacters obj = new DupCharacters();
System.out.println("String: Welcome");
System.out.println("---------------");
obj.countDupChars("Welcome");
System.out.println("\nString ITEngineer8995");
System.out.println("-----------------------");
obj.countDupChars("ITEngineer8995");
System.out.println("\nString: YoutubeChannel");
System.out.println("------------------------");
obj.countDupChars("YoutubeChannel");
}
}
Output:
String: Welcome
---------------
Chare2
String ITEngineer8995
-----------------------
Chare2
Charn2
Char92
String: YoutubeChannel
------------------------
Charu2
Chare2
Charn2
For the execution of the same do visit my YouTube Channel:


0 comments:
Post a Comment