0
0
KotlinProgramBeginner · 2 min read

Kotlin Program to Count Words in a String

You can count words in a string in Kotlin by splitting the string with split(" ") and then getting the size of the resulting list using words.size.
📋

Examples

InputHello world
Output2
InputKotlin is fun to learn
Output5
Input
Output0
🧠

How to Think About It

To count words, think of words as parts separated by spaces. Splitting the string by spaces creates a list of words. Counting the number of items in this list gives the total words. We must also handle empty strings carefully so they don't count as one word.
📐

Algorithm

1
Get the input string.
2
Trim the string to remove extra spaces at the start and end.
3
Check if the string is empty after trimming; if yes, return 0.
4
Split the string by spaces to get a list of words.
5
Count the number of words in the list.
6
Return the count.
💻

Code

kotlin
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)}")
}
Output
Word count: 5
🔍

Dry Run

Let's trace the input "Kotlin is fun to learn" through the code

1

Trim input

Input: "Kotlin is fun to learn" -> Trimmed: "Kotlin is fun to learn"

2

Check if empty

Trimmed string is not empty, continue

3

Split string

Split by space -> ["Kotlin", "is", "fun", "to", "learn"]

4

Count words

List size is 5

5

Return count

Return 5

StepActionValue
1Trim input"Kotlin is fun to learn"
2Check emptyNot empty
3Split string["Kotlin", "is", "fun", "to", "learn"]
4Count words5
5Return count5
💡

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

Using Regex to split by any whitespace
kotlin
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)}")
}
This method handles multiple spaces and tabs between words better than splitting by a single space.
Using filter and count
kotlin
fun countWordsFilter(text: String): Int {
    return text.split(" ").filter { it.isNotBlank() }.count()
}

fun main() {
    val input = "  Kotlin  is  fun  "
    println("Word count: ${countWordsFilter(input)}")
}
This method removes empty strings from the split list, counting only real words.

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.

ApproachTimeSpaceBest For
Split by spaceO(n)O(n)Simple cases with single spaces
Split by regex whitespaceO(n)O(n)Strings with multiple or mixed whitespace
Filter after splitO(n)O(n)Ignoring empty words after splitting
💡
Always trim your string before splitting to avoid counting empty spaces as words.
⚠️
Beginners often forget to trim the string, causing extra empty words to be counted.