Task description: Write a function, which counts the letters, spaces, number and special characters in string.
My implementation:
fun getPartsCount(str: String): Array<Int> {
val nums = "[0-9]".toRegex().findAll(str)
val letters = "[a-zA-Z]".toRegex().findAll(str)
val spaces = " ".toRegex().findAll(str)
var others = str.count() - nums.count() - letters.count() - spaces.count()
return arrayOf(nums.count(), letters.count(), spaces.count(), others)
}
fun main() {
print("Please enter a string > ")
val userInput = readLine()
if (!userInput.isNullOrEmpty()) {
val results = getPartsCount(userInput)
println("Numbers: ${results[0]}, Letters: ${results[1]}, " +
"Spaces: ${results[2]}, Others: ${results[3]}")
} else {
println("No input provided.")
}
}
I solved the task using Regular Expressions, but is there a better way in Kotlin for accomplishing the task?
What's your opinion about returning the results in an array? What would you do different and why?