Home » Scala programs » Scala string programs

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

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.

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.