Kotlin Program to Count Words in a String
split(" ") and then getting the size of the resulting list using words.size.Examples
How to Think About It
Algorithm
Code
fun countWords(text: String): Int {
val trimmed = text.trim()
if (trimmed.isEmpty()) return 0
val words = trimmed.split(" ")
return words.size
}
fun main() {
val input = "Kotlin is fun to learn"
println("Word count: ${countWords(input)}")
}Dry Run
Let's trace the input "Kotlin is fun to learn" through the code
Trim input
Input: "Kotlin is fun to learn" -> Trimmed: "Kotlin is fun to learn"
Check if empty
Trimmed string is not empty, continue
Split string
Split by space -> ["Kotlin", "is", "fun", "to", "learn"]
Count words
List size is 5
Return count
Return 5
| Step | Action | Value |
|---|---|---|
| 1 | Trim input | "Kotlin is fun to learn" |
| 2 | Check empty | Not empty |
| 3 | Split string | ["Kotlin", "is", "fun", "to", "learn"] |
| 4 | Count words | 5 |
| 5 | Return count | 5 |
Why This Works
Step 1: Trim the string
We use trim() to remove spaces at the start and end so they don't count as empty words.
Step 2: Check for empty string
If the trimmed string is empty, it means there are no words, so we return 0.
Step 3: Split by spaces
Splitting the string by space creates a list where each element is a word.
Step 4: Count words
The size of the list is the total number of words in the string.
Alternative Approaches
fun countWordsRegex(text: String): Int {
val trimmed = text.trim()
if (trimmed.isEmpty()) return 0
val words = trimmed.split(Regex("\\s+"))
return words.size
}
fun main() {
val input = "Kotlin is fun\tto learn"
println("Word count: ${countWordsRegex(input)}")
}fun countWordsFilter(text: String): Int {
return text.split(" ").filter { it.isNotBlank() }.count()
}
fun main() {
val input = " Kotlin is fun "
println("Word count: ${countWordsFilter(input)}")
}Complexity: O(n) time, O(n) space
Time Complexity
The program scans the entire string once to trim and split it, so time grows linearly with string length.
Space Complexity
Splitting creates a list of words, which requires extra space proportional to the number of words.
Which Approach is Fastest?
Splitting by a simple space is fast but less flexible; regex splitting handles complex whitespace but is slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Split by space | O(n) | O(n) | Simple cases with single spaces |
| Split by regex whitespace | O(n) | O(n) | Strings with multiple or mixed whitespace |
| Filter after split | O(n) | O(n) | Ignoring empty words after splitting |