简体   繁体   English

Scala:如何对多个字母使用计数功能

[英]Scala: How can I use a count function for multiple letters

Ok so I'm trying to check the number of occurrences of a, b and c in a string and I'm trying to use a count function to do. 好的,所以我尝试检查字符串中a,b和c的出现次数,并且尝试使用count函数来执行操作。 Can I use that with multiple letters? 我可以使用多个字母吗?

You can use scala Set 您可以使用scala Set

  val inSet = Set('a', 'b', 'c')
  "cat".count(inSet)

Scala Set has apply method with same behavior as contains , so when you do count(inSet) effectively you are doing count(c => inSet.apply(c)) which is equal to count(c => inSet.contains(c)) Scala Set具有与contains相同的apply方法,因此当您有效地进行count(inSet)您正在执行的count(c => inSet.apply(c))等于count(c => inSet.contains(c))

对于每个字符,只需检查此字符是否在您感兴趣的字符列表中,

"cat".count( ( c: Char ) => List( 'a', 'b', 'c').contains( c ) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM