Hello, In this post we will see Program to find duplicate characters in a string in Java, find duplicate characters in a string java without using hashmap, program to remove duplicate characters in a string in java etc.
Table of Contents
Program to find duplicate characters in String in a Java
package Practice; import java.util.HashMap; import java.util.Set; public class FindDuplicateCharinWord { public static void main(String[] args) { String str = "Pune is a green city"; String s1 = str.replaceAll("\\s", ""); // Converting given string to char array char[] c = s1.toCharArray(); // Creating HashMap containing char as key and it's occurrences as value HashMap<Character, Integer> m = new HashMap<Character, Integer>(); // Checking each character of c for (Character ch : c) { if (m.containsKey(ch)) { m.put(ch, m.get(ch) + 1); } else { m.put(ch, 1); } } // getting a set which containing all keys of m hashmap Set<Character> s = m.keySet(); for (Character c1 : s) { if (m.get(c1) > 1) { System.out.println(c1 + "-->" + m.get(c1)); } } } }
Output:
e–>3
i–>2
n–>2
Explanation: In the above program, we have used HashMap and Set for finding the duplicate character in a string. First we have converted the string into array of character. Then create a hashmap to store the Characters and their occurrences. Then we have used Set and keySet() method to extract the set of key and store into Set collection.
Program to remove duplicate characters in a string in java
If you are not using HashMap then you can iterate the passed String in an outer and inner loop and check if the characters are equal or not. If equal, then increment the count. In case characters are equal you also need to remove that character from the String so that it is not counted again in further iterations.
public class DuplicateChars { public static void main(String[] args) { findDuplicateCharsWithCount("kakatua parrot is a bird"); System.out.println("------------"); findDuplicateCharsWithCount("John was jealous"); System.out.println("------------"); findDuplicateCharsWithCount("rats"); } private static void findDuplicateCharsWithCount(String str) { System.out.println("Duplicates in- "+ str); int count; for(int i = 0; i < str.length(); i++) { count = 1; //Take one char at a time char c = str.charAt(i); // don't count the spaces if(c == ' ') continue; for(int j = i + 1; j < str.length(); j++) { if(c == str.charAt(j)) { count++; // remove the char so that it is not picked again // in another iteration str = str.substring(0, j) + str.substring(j+ 1); } } if(count > 1) { System.out.println(c + " found " + count + " times"); } } } }
Watch this video-
I hope you liked this post. Happy Learning 🙂
You Must Learn:
3 Ways of Reverse a Number in Java
5 Different Ways of Swap Two Numbers in Java