How to find the largest and the smallest word in a string with Kotlin

1 Answer

0 votes
fun findLargestAndSmallestWords(s: String): Pair<String?, String?> {
    val words = s.split("\\s+".toRegex())
    var smallest: String? = null
    var largest: String? = null

    for (word in words) {
        if (smallest == null || word.length < smallest.length) {
            smallest = word
        }
        if (largest == null || word.length > largest.length) {
            largest = word
        }
    }

    return Pair(smallest, largest)
}

fun main() {
    val s = "Kotlin programming language cross-platform and fun"
    
    val (smallest, largest) = findLargestAndSmallestWords(s)
    
    println("Smallest word: $smallest")
    println("Largest word: $largest")
}
 

 
/*
run:

Smallest word: and
Largest word: cross-platform
 
*/

 



answered Dec 28, 2024 by avibootz
edited Dec 28, 2024 by avibootz
...