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

发布于 2024-12-12 00:20:55 字数 111 浏览 0 评论 0 原文

Scala 是否有一种原生方法来计算字符串中某个字符的所有出现次数?

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

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

谢谢!

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

If so, how do I do it?

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

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千鲤 2024-12-19 00:20:55
"hello".count(_ == 'l') // returns 2
"hello".count(_ == 'l') // returns 2
懒猫 2024-12-19 00:20:55

我不使用Scala,甚至不使用java,但谷歌搜索“Scala string”将我带到这里

其中包含:

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

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

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

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.

烟火散人牵绊 2024-12-19 00:20:55

您还可以使用 sliding 采取更高级别的方法来查看另一个字符串中的子字符串出现情况:

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

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

def countSubstring(str: String, sub: String): Int =
  str.sliding(sub.length).count(_ == sub)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文