Используйте Map<Integer, Integer>
(ключ: символ, значение: количество символов) для хранения количества символов.
Вам нужно только один раз зациклить персонажей:
String input = "this is input string";
Map<Integer, Integer> charCount = new LinkedHashMap<>();
for (int c : input.toCharArray()) {
if (!charCount.containsKey(c)) {
charCount.put(c, 1);
} else {
charCount.put(c, charCount.get(c) + 1);
}
}
// Here you print the char count:
for (Entry<Integer, Integer> entry : charCount.entrySet()) {
// (char) entry.getKey() is the character
// entry.getValue() is number of occurence
}
БезMap
:
int[][] count = new int[MAX_CHAR][2];
for (int c : input.toCharArray()) {
count[c][0] += 1; // Increase occurrence by 1
count[c][1] = 1; // Mark this character exists in string
}
// Here you can print the count of char per character
// Not that, you can use count[c][1] to determine that if the character exists in your String
for (int i = 0; i < MAX_CHAR; i++) {
if (count[i][1] == 1) {
System.out.println("Char: " + (char) i + " Occurence: " + count[i][0]);
}
}
Редактировать Как подсказывает @oreh, нам даже не нужны двухмерные массивы:
int[] count = new int[MAX_CHAR];
for (int c : input.toCharArray()) {
count[c][0] += 1; // Increase occurrence by 1
}
for (int i = 0; i < MAX_CHAR; i++) {
if (count[i] > 0) {
System.out.println("Char: " + (char) i + " Occurence: " + count[i]);
}
}