Let's say I have the string "UNDERSTAND"
. Now let's say I want to count the occurrences of each letter in the string. So from my example I would want something like this,
U - 1
N - 2
D - 2
E - 1
R - 1
S - 1
T - 1
A - 1
How can I do this?
Let's say I have the string "UNDERSTAND"
. Now let's say I want to count the occurrences of each letter in the string. So from my example I would want something like this,
U - 1
N - 2
D - 2
E - 1
R - 1
S - 1
T - 1
A - 1
How can I do this?
You could convert the string to a char array, and add those to a map where the key is the character and the value its count.
Map<Character, Integer> count = new TreeMap<Character, Integer>();
for (char c : yourString.toCharArray()) {
if (count.containsKey(c)) {
count.put(c, (int) count.get(c) + 1);
} else {
count.put(c, 1);
}
}
Printing count
when yourString = "UNDERSTAND"
gives:
{A=1, D=2, E=1, N=2, R=1, S=1, T=1, U=1}
As seen on ideone.
If you don't get the idea, here's a pseudo-code version of it (aka Python):
string = 'UNDERSTAND'
count = {} # new map (dict)
for char in string:
if char in count:
count[char] = count[char] + 1
else:
count[char] = 1
Also available on ideone
You can use a HashMultiset
from the guava libraries.
Multiset<Character> set = new HashMultiset<Character>();
for (char c : string.toCharArray()) {
set.add(c);
}
The Multiset
stores each item (character) together with the number of times it was added.
So you can iterate:
for (Character c : set) {
System.out.println(c + " - " + set.getcount(c));
}
But in case it is a homework, I assume this approach would be frowned upon by the teachers. Figure out how to implement it without the help of additional libraries.
Java answer
Note: please study this code, don't just copy.
public static void main(String[] args) {
String text = "UNDERSTAND";
Map<String,Integer> countMap = new HashMap<String,Integer>();
for(int i=0; i < text.length(); i++) {
String letter = String.valueOf(text.charAt(i));
if (countMap.get(letter) == null) {
countMap.put(letter, 1);
} else {
Integer temp = countMap.get(letter);
temp++;
countMap.put(letter, temp++);
}
}
System.out.println(countMap);
}
Javascript answer (just for quick test)
var text = "UNDERSTAND";
var count = new Array();
for(i=0; i < text.length; i++) {
var letter = text[i];
if (count[letter] == null) {
count[letter] = 1;
} else {
count[letter]++;
}
}
console.log(count);
Why use complex data structures that require hashing/pointers...etc, when you can solve it with the most simple (and fast) algorithm.
public static void main(String[] args) {
String s = "UNDERSTOOD";
int res[] = new int[256];
for(int i=0 ; i<s.length() ; i++)
{
res[s.charAt(i)]++;
}
for(int i=0 ; i<res.length ; i++)
{
if(res[i] !=0)
{
System.out.println(""+(char)i+" : "+res[i]);
}
}
}
The print:
D : 2
E : 1
N : 1
O : 2
R : 1
S : 1
T : 1
U : 1
Roni