Here, we are implementing programs to perform following operations on a string,
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
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) } }
This string is 'Learn programming at IncludeHelp' Count of charceters in the string: 32
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
1) Counting occurrence of a character
The count() method in Scala is used to count the occurrence of characters in the string.
Syntax:
The function will return the count of a specific character in the string.
Program to count the occurrence of a character in a string
Output
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
Output
need an explanation for this answer? contact us directly to get an explanation for this answer