aspose file tools*
The moose likes Beginning Java and the fly likes Count similar characters in a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Count similar characters in a String" Watch "Count similar characters in a String" New topic
Author

Count similar characters in a String

Anjali S Sharma
Ranch Hand

Joined: Jun 29, 2005
Posts: 279
I have a String such as

String s = "sssssaaagg";

I need to count the number ot times each character is repreated. In this case
s-5
a-3
g-2
Please give me some pointers as to how should I proceed it.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42608
    
  65
You can iterate through all the characters like this:

for (int i=0; i<s.length; i++) {
char ch = s.charAt(i);
...
}

For the result, keep a HashMap with the character as key and the number of its occurrences as the value.


Ping & DNS - my free Android networking tools app
madhup narain
Ranch Hand

Joined: Dec 14, 2004
Posts: 148
hi..
ever heard of charAt in the String class ....

try it
Regards


Money for nothing and Java for Free
SCJP, SCWCD
Jeffrey Spaulding
Ranch Hand

Joined: Jan 15, 2004
Posts: 149
You could

* travel through the String char-per-char,
* use the char you have in hand as a key to a Hashmap
* and store the tally for this key as value in the Hashmap

But i'm sure there are a million other possibilities

What do the other cowboys think ?

J.
Anjali S Sharma
Ranch Hand

Joined: Jun 29, 2005
Posts: 279
Thanks a lot.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Do you need to count the occurence of adjacent repeated characters? Or just the count of each unique character in the word? Either way, the above hints should provide a place to start. If you get stuck, please let us know what you have tried and we can help from there.

Layne


Java API Documentation
The Java Tutorial
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Count similar characters in a String