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.

Recommended Answers

All 4 Replies

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...

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?

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);

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.