This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets forum!
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: 41060
    
  43
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Count similar characters in a String
 
Similar Threads
using getopt() in Java
Count Objects !
regular expression
variable problem
Retrieving values