954,529 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Counting occurances of characters in string

I am writing a program using J2ME and my goal is to count how many times each character appears in a string.

I am not very good at java so the way i see i should do this is create 2 arrays.
First array is used to hold characters. Second array is used to keep count

The program goes through checks if the first character of the string is in the first array. If it isn't, then put it in the first position in the array and add 1 to its count in the second array. This loops through until every character has been counted.

I feel this method seems kinda long winded so i was wondering if someone could offer me a better way of doing it?

I have searched and people have said use hash maps. I dont know what they are but it looks like they are not available in J2ME anyway.

lethal.b
Newbie Poster
17 posts since Mar 2010
Reputation Points: 10
Solved Threads: 0
 

Remember Java chars are numeric - ordinary characters correspond to integer values under 128. If you have an array of 127 ints you can use a char as the index to access an element of the array and increment it...

JamesCherrill
Posting Genius
Moderator
6,372 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

thanks for the reply,

So you mean i wouldn't need my first array then? Is the numeric value of the char the decimal for it in the ascii table?

Also if using the numeric value of the chars can it be used on the extended characters in the ascii table as well?

lethal.b
Newbie Poster
17 posts since Mar 2010
Reputation Points: 10
Solved Threads: 0
 

Yes, you only need one array.
Yes, the numeric value of the char the decimal for it in the ascii table.
Not exactly ... Java uses 16 bit UniCode to store characters, and these are only the same as ASCII for codes up to 127. ASCII extended characters are basically irrelevant in Java as UniCode handles all such symbols far better.
Having said all that, you don't really need to know the decimal equivalents, just use chars and they will work as both letters and numeric values as if by magic, eg

for (char c = 'a'; c <= 'z'; c++) System.out.print(c);
or
array['a']++;

JamesCherrill
Posting Genius
Moderator
6,372 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

ah i understand it now. Thanks for thelp. I guess i can mark this as solved

lethal.b
Newbie Poster
17 posts since Mar 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: