Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Java in General
Search Coderanch
Advance search
Google search
Register / Login
Win a copy of
Darcy DeClute's Scrum Master Certification Guide: The Definitive Resource for Passing the CSM and PSM Exams
this week in the
Agile and Other Processes
forum!
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
Devaka Cooray
Ron McLeod
Paul Clapham
Liutauras Vilda
Sheriffs:
paul wheaton
Jeanne Boyarsky
Tim Cooke
Saloon Keepers:
Stephan van Hulst
Tim Holloway
Tim Moores
Mikalai Zaikin
Carey Brown
Bartenders:
Forum:
Java in General
occurence of char in a string
suman deb
Ranch Hand
Posts: 54
posted 17 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
hi all,
how to find out the occurence of each char in a
string
? e.g.
for the string "HELLO" , the required out put is--
H - 1
E - 1
L - 2
o - 1
please help
Christophe Verré
Sheriff
Posts: 14691
16
I like...
posted 17 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
You could try with String.indexOf(int ch, int fromIndex), looping through the whole String.
[My Blog]
All roads lead to JavaRanch
Allan Morris
Greenhorn
Posts: 4
posted 17 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Hi, a map is a good data structure, pairing each character to a count. You can do it like this using the Collections framework:
import java.util.*; /*Count the occurences of characters in a string. **/ public class QuickTest { private static String data = "Hello"; public static void main(String[] args) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); char[] tempData = data.toCharArray(); //Count the characters for(char current : tempData) { if(map.containsKey(current)) { map.put(current, map.get(current)+1); } else map.put(current, 1); } /** Output results, * It's necessary to create a set view because maps don't provide an iterator */ Set<Map.Entry<Character, Integer>> results = map.entrySet(); for(Map.Entry<Character, Integer> entry : results) { System.out.print(entry.getKey() + " - "); System.out.println(entry.getValue()); } } }
[ September 05, 2006: Message edited by: Allan Morris ]
money grubbing section goes here:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
Substring and Searching
replace char with string
Parse text between angle brackets
Password checker (occurence)
an interview question to count occurence of characters
More...