File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Count similar characters in a String

 
Anjali S Sharma
Ranch Hand
Posts: 279
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
madhup narain
Ranch Hand
Posts: 148
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi..
ever heard of charAt in the String class ....

try it
Regards
 
Jeffrey Spaulding
Ranch Hand
Posts: 149
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 279
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot.
 
Layne Lund
Ranch Hand
Posts: 3061
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic