How to count the letters, spaces, numbers and other characters of a string in Kotlin

2 Answers

0 votes
class CountCharacters_Kotlin {
    companion object {
        fun countCharacters(s: String) {
            val arr = s.toCharArray()

            var letter = 0
            var spaces = 0
            var numbers = 0
            var otherchars = 0

            for (i in s.indices) {
                when {
                    arr[i].isLetter() -> letter++
                    arr[i].isDigit() -> numbers++
                    arr[i].isWhitespace() -> spaces++
                    else -> otherchars++
                }
            }
            println("letter: $letter")
            println("space: $spaces")
            println("number: $numbers")
            println("other: $otherchars")
        }

        @JvmStatic
        fun main(args: Array<String>) {
            val s = "Ko12tlin \$%     Prog()ramming   99 !!!"
            
            countCharacters(s)
        }
    }
}

 
 
/*
run:
   
letter: 17
space: 10
number: 4
other: 7
   
*/

 



answered Nov 24, 2024 by avibootz
edited Nov 24, 2024 by avibootz
0 votes
class CountCharacters_Kotlin {
    companion object {
        fun countCharacters(s: String) {
            val letters = s.count { it.isLetter() }
    		val spaces = s.count { it.isWhitespace() }
    		val numbers = s.count { it.isDigit() }
    		val otherchars = s.count { !it.isLetterOrDigit() && !it.isWhitespace() }


            println("letter: $letters")
            println("space: $spaces")
            println("number: $numbers")
            println("other: $otherchars")
        }

        @JvmStatic
        fun main(args: Array<String>) {
            val s = "Ko12tlin \$%     Prog()ramming   99 !!!"
            
            countCharacters(s)
        }
    }
}

 
 
/*
run:
   
letter: 17
space: 10
number: 4
other: 7
   
*/

 



answered Nov 24, 2024 by avibootz
...