Sunday, 26 July 2015

Find duplicate characters in String ?

package com.JavaInterview.Programs;

/**
 * Find Out Duplicate
 * 
 * @author:http://javainterviewprograms.blogspot.in/
 * 
 */
import java.util.*;
import java.util.HashMap;
import java.util.Set;
public class DuplicateCharacters {

 public void findDuplicate(String str)
 {
  char[] charc=str.toCharArray();
  Map<Character,Integer> mapc=new HashMap<Character,Integer>();
  for(Character ch:charc)
  {
   if(mapc.containsKey(ch))
   {
    mapc.put(ch,mapc.get(ch)+1);
   }
   else
   {
    mapc.put(ch,1);
   }
  }
  Set<Map.Entry<Character, Integer>> entrySet=mapc.entrySet();
  System.out.printf("list of duplicates characters in string '%s' %n",str);
  for(Map.Entry<Character, Integer> entry:entrySet)
  {
   if(entry.getValue()>1)
   {
    System.out.printf("%s:%d%n",entry.getKey(),entry.getValue());
   }
  }
 
 }
 public static void main(String args[])
 {
  Scanner input=new Scanner(System.in);
  System.out.println("Please enter the string to find out duplicate Characters :");
  String str=input.next();
  DuplicateCharacters dc=new DuplicateCharacters();
  dc.findDuplicate(str);
 }

}

Output:
Please enter the string to find out duplicate Characters :
papaya
list of duplicates characters in string 'papaya' 
a:3
p:2


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...