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

Scala | Counting total number of characters in a string: Here, we will learn how to count the number of characters in a string in Scala programming language?
Submitted by Shivang Yadav, on April 24, 2020 [Last updated : March 10, 2023]

Scala – Counting characters of a String

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

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.

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

Scala 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

Scala String Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.