How to count the white spaces in a string in Kotlin

1 Answer

0 votes
fun countWhitespaceCharacters(str: String): Int {
    var count = 0
    val length = str.length

    for (i in 0 until length) {
        if (str[i].isWhitespace()) {
            count++
        }
    }

    return count
}

fun main() {
    val str = "Kotlin \n  Programming \r Language \t "

    println("Total white spaces: ${countWhitespaceCharacters(str)}")
}



/*
run:
  
Total white spaces: 10
  
*/

 



answered Oct 20, 2024 by avibootz

Related questions

1 answer 121 views
1 answer 120 views
1 answer 99 views
1 answer 116 views
1 answer 91 views
...