Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

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
...