Given a string, count the number of alphabets, digits & other characters in it.
fun main() {
val text = "namaste world 1 !"
val occurrences = text
.groupBy {
when {
it.isLetter() -> "Alphabets"
it.isDigit() -> "Digits"
else -> "Other"
}
}.mapValues {
it.value.count()
}
println(occurrences)
}
// Output : {Alphabets=12, Other=4, Digits=1}
Working :
- Firstly, we use the groupBy function to classify each character in the string as either “Alphabets”, “Digit” or “Other”. This returns a
Map<String, List<Char>>
where key is the group name and value is the list of characters in that group. - Then, we use the mapValues function calculate the number of characters in each class. Thus
Map<String, List<Char>>
is converted toMap<String, Int>
where key is the group name and value is the number of characters in that group.