package com.zia.test;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class findDuplicateCharacter {
/**
* @param args
*/
public static void findByusingMap(String str) {
// HashMap with character and number of times they appear in given
// String argument
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
char[] charArr = str.toCharArray();
for (char value : charArr) {
if (Character.isLetter(value)) {
if (charMap.containsKey(value)) {
charMap.put(value, charMap.get(value) + 1);
} else {
charMap.put(value, 1);
}
}
}
Set<Character> charString = charMap.keySet();
System.out.println("Duplicate Characters In =" + str);
// set iteration
for (Character ch : charString) {
if (charMap.get(ch) > 1) {
// If any char occur more than 1, printing it's count
System.out.println(ch + " : " + charMap.get(ch));
}
}
}
public static void main(String[] args) {
findDuplicateCharacter.findByusingMap("Hello How are You Doing?");
findDuplicateCharacter.findByusingMap("Hope you all are doing good");
findDuplicateCharacter.findByusingMap("Thank you very much for reading this");
}
}
OutPut:-
Duplicate Characters In =Hello How are You Doing?
e : 2
o : 4
l : 2
H : 2
Duplicate Characters In =Hope you all are doing good
g : 2
d : 2
e : 2
a : 2
o : 5
l : 2
Duplicate Characters In =Thank you very much for reading this
e : 2
a : 2
n : 2
o : 2
h : 3
i : 2
u : 2
r : 3
y : 2
Its very simple program no need to explain,get the character array from String, iterate through that and put it in a Map with character and their count.Then get a Set containing all keys of map and iterate through Set and print characters which have appeared more than once.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
No comments:
Post a Comment