简体   繁体   English

Scala-计算字符串中的特定字符(按功能样式)

[英]Scala - Count a specific Charecter in a String (in a functional style)

I can count a specific string with the below code 我可以用下面的代码计算一个特定的字符串

 var count = 0
for (i <- "HelloWorldHHHH") {
if (i == 'H') {
  count = count + 1
}
println(count)

or use builtins like 或使用诸如

"HelloWorldHHHH".count(_ == 'H')

can someone help me to write the same functionality using pure functional way 有人可以帮助我使用纯功能方式编写相同的功能吗

I tried the below, but not sure where i am going wrong 我尝试了以下操作,但是不确定我要去哪里

val count1 = "Hello".foldLeft(0)((x,_) match { case k if(k == 'h') => x +1})

the last code has some errors, can someone help me to fix the error or give the correct solution 最后的代码有一些错误,有人可以帮助我修复错误或提供正确的解决方案

"HelloWorldHHHH".count(_ == 'H') is already in pure functional style, and it seems the preferred option to me since it is very short and readable. "HelloWorldHHHH".count(_ == 'H')已经是纯函数式的,对我来说似乎是首选,因为它非常简短易读。

More options: 更多选择:

folding : 折叠

"HelloWorldHHHH".foldLeft(0){case(count, char) => if (char == 'H') count + 1 else count }

summing after a for-comprehension . 理解后总结 notice that you can use a guard (if): 请注意,您可以使用防护装置(如果有):

val hs = for {
  i <- "HelloWorldHHHH"
  if i == 'H'
} yield 1
hs.sum

collecting : 收集

"HelloWorldHHHH".collect{ case 'H' => 1 }.sum

In case you actually want to do this in production code, I suggest to use the stdlib count method: 如果您确实想在生产代码中执行此操作,我建议使用stdlib count方法:

"HelloWorldHHHH".count(_ == 'H')

For learning purposes you can roll your own with foldLeft : 出于学习目的,您可以使用foldLeft自己foldLeft

"HelloWorldHHHH".foldLeft(0) { case (sum, char) =>
  if (char == 'H') sum + 1 else sum
}

You can drop the if and just insert your character in the case block 您可以删除if并将字符插入case块

"Hello".foldLeft(0) {(acc,c) => c match {
    case 'l' => acc + 1
    case _ => acc
  }
}

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

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