Organizational Research By

Surprising Reserch Topic

Java Program to find duplicate Characters in a String


This program would find out the duplicate characters in a String and would display the count of them.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
public class Details {
 
  public void countDupChars(String str){
 
    //Create a HashMap
    Map map = new HashMap();
 
    //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 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 a[]){
    Details obj = new Details();
    System.out.println("String: BeginnersBook.com");
    System.out.println("-------------------------");
    obj.countDupChars("BeginnersBook.com");
  
    System.out.println("\nString: ChaitanyaSingh");
    System.out.println("-------------------------");
    obj.countDupChars("ChaitanyaSingh");
 
    System.out.println("\nString: #@$@!#$%!!%@");
    System.out.println("-------------------------");
    obj.countDupChars("#@$@!#$%!!%@");
  }
}
Output:

String: BeginnersBook.com
-------------------------
Char e 2
Char B 2
Char n 2
Char o 3

String: ChaitanyaSingh
-------------------------
Char a 3
Char n 2
Char h 2
Char i 2

String: #@$@!#$%!!%@
-------------------------
Char # 2
Char ! 3
Char @ 3
Char $ 2
Char % 2
asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
90 views



Related Hot Questions



Government Jobs Opening


...