1

So I have a program that counts the number of occurrences of each letter in a string, and for that I use

int[] charAmount = new int[30]; for(int i = 0; i<text.length(); i++){ char sign = text.charAt(i); int value = sign; if(value >= 97 && value <= 122){ charAmount[value-97]++; // 97 = 'a' } 

This works fine, but I also need to cover the letters 'æ' (230), 'ø' (248) & 'å' (229). How can I "assign" those three letters to the 26, 27 & 29th index of the charAmount array without using if tests or a switch?

EDIT: The code presented above is not the whole block, I also have a switch for the letters in question, but I am looking for a better solution.

BONUS PROBLEM: When I try to enter a string like "æææ" or something, the value of 'æ' is suddenly 8216. I use a Scanner to read the input.

1
  • just add conditions for each of these characters. Theres no simpler solution than that. Or use a Map for further extensibility Commented Sep 28, 2015 at 7:50

2 Answers 2

1

Try this after your if:

else if (value == 230) charAmount[26]++; else if (value == 248) charAmount[27]++; else if (value == 229) charAmount[29]++; 

You can also do an array of the chars and their associations, the array will look like this:

spChars_to_Chars = 0 => 96 1 => 97 ... 229 => 29 230 => 26 ... 248 => 27 

And then just do this in your if:

charAmount[spChars_to_Chars[value]]++; 
Sign up to request clarification or add additional context in comments.

6 Comments

Well that was my original solution, but it's not very smooth, is there no way to make it more seamless, any way to temporarily change the value of certain chars for example?
You could do an array, that will look like this: 97 => 0 98 => 1 ... 230 => 26 ... 248 => 27 ... 229 => 29 And then just do charAmount[array[value]]++;
@Alexel, Why don't you update your answer to what you did in your comment? The answer is so normal. But the answer in comment is lovely and brilliant.
Actually I have a 'bonus problem': when I try to enter a string like "æææ" or something, the value of 'æ' is suddenly 8216. I use a Scanner to read the input.
Could you print the char you have instead of the value ? try print sign and give us the result please !
|
0

If you can use external libraries, I would rather try using Apache commons. They provide a function to count the matches of a given substring (your characters) in a bigger string:

StringUtils.countMatches(...)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.