• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Count similar characters in a String

 
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi..
ever heard of charAt in the String class ....

try it
Regards
 
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot.
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic