Skip to content

Word & Character Counter — Kotlin source

Live word, character, sentence, and paragraph counts plus reading-time estimate as you type.

This is the Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.

// word-counter — Kotlin port: word / character / sentence / paragraph counts + 200-wpm reading-time estimate.
//
// Display snippet: ports the counters from the TypeScript lib (src/lib/wordCount.ts). Kotlin strings
// are UTF-16, so length is the same unit the TS reference counts.

object WordCounter {
    private val WHITESPACE = Regex("\\s+")
    private val BLANK_LINE = Regex("\\n{2,}")
    private val SENTENCE = Regex("[^.!?]+[.!?]+")

    // Words: split on whitespace runs, ignoring empties — blank input -> 0.
    fun countWords(t: String): Int = t.trim().split(WHITESPACE).count { it.isNotBlank() }

    // Total character count, whitespace included.
    fun countChars(t: String): Int = t.length

    // Character count with all whitespace removed.
    fun countCharsNoSpaces(t: String): Int = t.count { !it.isWhitespace() }

    // Sentences: maximal runs of non-terminators each closed by one or more
    // of . ! ? — the TS regex /[^.!?]+[.!?]+/g.
    fun countSentences(t: String): Int = SENTENCE.findAll(t).count()

    // Paragraphs separated by one or more blank lines; blank segments don't count.
    fun countParagraphs(t: String): Int = t.split(BLANK_LINE).count { it.isNotBlank() }

    // Reading time at 200 wpm: 0 for empty input, otherwise >= 1 minute.
    // (words + 100) / 200 reproduces round(words / 200.0).
    fun readingTimeMin(words: Int): Int =
        if (words <= 0) 0 else maxOf(1, (words + 100) / 200)
}

fun main() {
    val text = "CosmoDev counts words. Live totals update as you type!\n\n" +
        "Second paragraph? Two sentences - each with words. Zero logins needed."
    println("words:       ${WordCounter.countWords(text)}")          // 20
    println("chars:       ${WordCounter.countChars(text)}")          // 126
    println("no spaces:   ${WordCounter.countCharsNoSpaces(text)}")  // 106
    println("sentences:   ${WordCounter.countSentences(text)}")      // 5
    println("paragraphs:  ${WordCounter.countParagraphs(text)}")     // 2
    println("reading min: ${WordCounter.readingTimeMin(WordCounter.countWords(text))}") // 1
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →