Monday, 10 September 2018

How to display duplicate characters in given a string using java

package com.java.collections;

import java.util.HashMap;
import java.util.Iterator;

public class DuplicateCharacters {
   
    static void findDuplicateCharacters(String str) {
       
        HashMap<Character, Integer> hm = new HashMap<>();
       
        for(int i=0; i<str.length();i++)
        {
            char c = str.charAt(i);
           
            if(hm.get(c)!=null)
            {
                hm.put(c, hm.get(c)+1);
            }
            else
            {
                hm.put(c, 1);
            }
                       
        }
           //System.out.println(hm);
        Iterator<Character> c = hm.keySet().iterator();
        while(c.hasNext())
        {
            char temp = c.next();
            if(hm.get(temp)>1)
            {
                System.out.println("the Character " + temp + " appeared " + hm.get(temp) + " times");
            }
        }
    }

    public static void main(String[] args) {
       
        findDuplicateCharacters("i i am am java java and and");

    }

}

No comments:

Post a Comment

If you Like my blog Spread it and help friends for whom this blog is useful for their career.