scala 字符串数组
Here, we are implementing programs to perform following operations on a string,
在这里,我们正在实现程序以对字符串执行以下操作,
Counting occurrence of a character
计算字符的出现
Counting total number characters in a string / length of the string
计算字符串中的字符总数/字符串长度
1)计算一个字符的出现 (1) Counting occurrence of a character)
The count() method in Scala is used to count the occurrence of characters in the string.
Scala中的count()方法用于计算字符串中字符的出现。
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)计算字符串中的字符总数/字符串的长度 (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
翻译自: https://www.includehelp.com/scala/how-to-count-the-number-of-characters-in-a-string-in-scala.aspx
scala 字符串数组