-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDuplicateCharacters.java
More file actions
42 lines (30 loc) · 1.09 KB
/
DuplicateCharacters.java
File metadata and controls
42 lines (30 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.company.Assign4;
import java.util.HashMap;
import java.util.Map;
//WAP to print duplicates characters from a string
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "Hello World";
printDuplicateCharacters(str);
}
public static void printDuplicateCharacters(String str) {
str = str.toLowerCase();
Map<Character, Integer> charCountMap = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isAlphabetic(c)) {
if (charCountMap.containsKey(c)) {
charCountMap.put(c, charCountMap.get(c) + 1);
} else {
charCountMap.put(c, 1);
}
}
}
System.out.println("Duplicate characters in the string:");
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + " - count: " + entry.getValue());
}
}
}
}