Q:

How to count the number of characters in a string in Scala?

belongs to collection: Scala String Programs

0

Here, we are implementing programs to perform following operations on a string,

  1. Counting occurrence of a character
  2. Counting total number characters in a string / length of the string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

1) Counting occurrence of a character

The count() method in Scala is used to count the occurrence of characters in the string.

Syntax:

    string.count()

The function will return the count of a specific character in the string.

Program to count the occurrence of a character in a string

object myObject {
    def main(args: Array[String]) {
        val string = "Learn programming at IncludeHelp"
        val count = string.count(_ == 'r')
        println("This string is '" + string + "'")
        println("Count of 'r' in the string :" + count)
    }
}

Output

This string is 'Learn programming at IncludeHelp'
Count of 'r' in the string :3

2) Counting total number characters in a string / length of the string

We can count the total number of characters in the string. For this, we will convert the string to an array and then find the length of the array.

Program to count the total number of characters in the string

object myObject {
    def main(args: Array[String]) {
        val string = "Learn programming at IncludeHelp"
        val count = string.toCharArray.length
        println("This string is '" + string + "'")
        println("Count of charceters in the string: " + count)
    }
}

Output

This string is 'Learn programming at IncludeHelp'
Count of charceters in the string: 32

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to create a range of characters in Scala?... >>
<< Scala program to convert string to integer...