tags:

views:

247

answers:

5

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?

+2  A: 

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

NullUserException
a) you should've used a TreeMap instead of HashMap to get the letters sorted b) I don't think it's a good idea to spell out full solutions for homework problems. Still: it's good, so +1
seanizer
@seanizer b) Yeah, I guess. But there are other full solutions here so I figured it doesn't make a difference at this point.
NullUserException
+3  A: 

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.

Bozho
+1, excellent answer to homework
MAK
A: 

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);
Topera
You do realize for every ten times you ask someone "study this answer, don't copy it", nine of them won't do anything except cut and paste what you just typed, right? :-)
Dean J
Well, at least 10% will study. :)
Topera
You've got a point. I just always wonder the best way to answer the homework questions, and if there's a way to get more than 10% to do the small bit of thinking...
Dean J
+3  A: 
Jörg W Mittag
A: 

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

roni