scala 计算字符串中某个字符的所有出现次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7908930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:37:42  来源:igfitidea点击:

Count all occurrences of a char within a string

scala

提问by isea

Does Scala have a native way to count all occurrences of a character in a string?

Scala 是否有一种本地方式来计算字符串中字符的所有出现次数?

If so, how do I do it?

如果是这样,我该怎么做?

If not, do I need to use Java? If so, how do I do that?

如果没有,我需要使用Java吗?如果是这样,我该怎么做?

Thanks!

谢谢!

回答by Jean-Philippe Pellet

"hello".count(_ == 'l') // returns 2

回答by Joe McGrath

i don't use Scala or even java but google search for "Scala string" brought me to here

我不使用 Scala 甚至 Java,但谷歌搜索“Scala 字符串”将我带到这里

which contains :

其中包含 :

def
count (p: (Char) ? Boolean): Int
Counts the number of elements in the string which satisfy a predicate.
p
the predicate used to test elements.
returns
the number of elements satisfying the predicate p.
Definition Classes
TraversableOnce → GenTraversableOnce

Seems pretty straight forward but i dont use Scala so don't know the syntax of calling a member function. May be more overhead than needed this way because it looks like it can search for a sequence of characters. read on a different result page a string can be changed into a sequence of characters and you can probably easily loop through them and increase a counter.

看起来很简单,但我不使用 Scala,所以不知道调用成员函数的语法。这种方式可能比所需的开销更多,因为它看起来可以搜索一系列字符。在不同的结果页面上读取字符串可以更改为字符序列,您可以轻松地遍历它们并增加计数器。

回答by Johnny

You can also take a higher level approach to look into substring occurrences within another string, by using sliding:

您还可以使用更高级别的方法来查看另一个字符串中出现的子字符串,方法是sliding

def countSubstring(str: String, sub: String): Int =
  str.sliding(sub.length).count(_ == sub)