If I am given an ArrayList of strings, i.e. {"hello", "goodbye", "morning", "night"}
, how do I check how many a
's, b
's, c
's, etc. there are in the list?
The method must return an array of int
s, where position [0] is the numbers of a
's, etc. For example, the returnArray[1] = 1
, because there is one b
in the list. Is there a better way to do this than simply hardcoding each letter?
public static int[] getLetters( ArrayList<String> list) {
int [] result = new int[25];
if(list.contains('a')) {
result[0] = result[0] + 1;
}
return result;
}
Is there a better way than repeating the above strategy 25 more times?
You can use the char
as a means to address the array, for example...
ArrayList<String> list = new ArrayList<>(Arrays.asList(new String[]{"hello", "goodbye", "morning", "night"}));
int[] results = new int[26];
for (String value : list) {
for (char c : value.toCharArray()) {
// 'a' is the lowest range (0), but the ascii for 'a' is 97
results[c - 'a'] += 1;
}
}
Which results in...
[0, 1, 0, 1, 2, 0, 3, 2, 2, 0, 0, 2, 1, 3, 4, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0]
nb: This will only work for lower case characters, if you have any upper case characters, you'll get an array out of bounds error. You could put range checking in for each character to make sure it's between a
and z
, but that's up to you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With