Tuesday, November 27, 2018

Find Duplicate Characters in a String With Repetition Count Java Program

In this post we’ll see a Java program to find duplicate characters in a String along with repetition count of the duplicates.

Finding duplicates characters in a String and the repetition count program is easy to write using a HashMap but you may be asked to write it without using any Java collection. In this post we’ll see both solutions.

Java program to find duplicate characters in a String

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");
      }
    }
  }
}

Output

Duplicates in- kakatua parrot is a bird
k found 2 times
a found 5 times
t found 2 times
r found 3 times
i found 2 times
------------
Duplicates in- John was jealous
o found 2 times
a found 2 times
s found 2 times
------------
Duplicates in- rats

Java program to find duplicate characters in a String using HashMap

If you are writing a Java program to find duplicate characters in a String and displaying the repetition count using HashMap then you can store each char of the String as a key and starting count as 1 which becomes the value. In each iteration check if key already exists, if yes then increment the count (by accessing the value for that key).

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);
    char[] strArr = str.toCharArray();
    Map<Character, Integer> countMap = new HashMap<>();
    for(char c : strArr) {
      // We don't need to count spaces
      if(c == ' ')
        continue;
      if(countMap.containsKey(c)) {
        countMap.put(c, countMap.get(c) + 1);
      }else {
        countMap.put(c, 1);
      }
    }
    // Displaying the map values
    Set<Map.Entry<Character, Integer>> countSet = countMap.entrySet();
    for(Map.Entry<Character, Integer> entry  : countSet){
      if(entry.getValue() > 1) {
        System.out.println(entry.getKey() + " found " + entry.getValue() + " times");
      }
    }
  }
}

Output

Duplicates in- kakatua parrot is a bird
a found 5 times
r found 3 times
t found 2 times
i found 2 times
k found 2 times
------------
Duplicates in- John was jealous
a found 2 times
s found 2 times
o found 2 times
------------
Duplicates in- rats

That's all for this topic Find Duplicate Characters in a String With Repetition Count Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert String to Byte Array Java Program
  2. Add Double Quotes to a String Java Program
  3. Convert String to double in Java
  4. Java Program to Find First Non-Repeated Character in a Given String
  5. Unzip File in Java

You may also like-

  1. Compress And Decompress File Using GZIP Format in Java
  2. How to Create PDF in Java Using OpenPDF
  3. Producer-Consumer Java Program Using ArrayBlockingQueue
  4. Convert double to int in Java
  5. New Date And Time API in Java With Examples
  6. Exception Handling in Java Lambda Expressions
  7. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  8. Spring depends-on Attribute

No comments:

Post a Comment