Java find occurrences of a character in string ?
- In java, we can find the occurrences of each character in given string using for loop and hashmap.
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class occurences {
public static void main(String[] args) {
String str = "elephantELEPHANT";
char c[] = str.toCharArray();
Map<Character, Integer> hm = new HashMap<Character, Integer>();
for (char ch : c) {
if (hm.containsKey(ch)) {
hm.put(ch, hm.get(ch) + 1);
} else {
hm.put(ch, 1);
}
}
System.out.println("Final Hash Map with occurences of each character=\n" + hm);
System.out.println("we can also get each value using keySet()");
Set<Character> s = hm.keySet();
for (char cha : s) {
System.out.print(cha + "=" + hm.get(cha) + " ");
}
}
}
Output:
|
Java program find occurrences of a character in string |
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.