charOccurences property
Finds all character occurrences and returns count as:
List<Map<dynamic,dynamic>>
Example 1
String foo = 'esentis';
List occurrences = foo.charOccurrences; // returns '[{e:2},{i:1},{n:1},{s:2},]'
Implementation
List<Map<String, int>> get charOccurences {
if (this.isBlank) {
return [];
}
// ignore: omit_local_variable_types
List<Map<String, int>> occurrences = [];
var letters = this!.split('')..sort();
var checkingLetter = letters[0];
var count = 0;
for (var i = 0; i < letters.length; i++) {
if (letters[i] == checkingLetter) {
count++;
if (i == letters.length - 1) {
occurrences.add({checkingLetter: count});
checkingLetter = letters[i];
}
} else {
occurrences.add({checkingLetter: count});
checkingLetter = letters[i];
count = 1;
}
}
return occurrences;
}