my dog learned polymorphism*
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

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Count similar characters in a String" Watch "Count similar characters in a String" New topic

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
Please give me some pointers as to how should I proceed it.
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 41137
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
ever heard of charAt in the String class ....

try it

Money for nothing and Java for Free
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 ?

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.


Java API Documentation
The Java Tutorial
It is sorta covered in the JavaRanch Style Guide.
subject: Count similar characters in a String
Similar Threads
using getopt() in Java
Retrieving values
Count Objects !
regular expression
variable problem