scala 字符串数组_如何在Scala中计算字符串中的字符数?

scala 字符串数组

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)计算一个字符的出现 (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 字符串数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值