【问题标题】:What's the shortest way to count substring occurrence in string? (Elixir)计算字符串中子字符串出现的最短方法是什么? (灵药)
【发布时间】:2018-12-04 06:09:34
【问题描述】:

目前我一直在使用Regex.scan方法:

Regex.scan(~r/do/i, “Do. Or do not. There is no try.") |> length

在Ruby中,我们可以使用.scan方法:"Hello world".count "o" #=> 2

有没有更短的方法来用 Elixir 计算字符串中的子字符串?不需要花哨的正则表达式,我只需要计算一个字符串中有多少个子字符串。

【问题讨论】:

  • ruby 中的 String#count 仅适用于单个字符。您在 Elixir 中的示例计算了子字符串的数量,在 ruby​​ 中,可以为此执行 String#scan 。请澄清您的问题。
  • 我会小心不要将“短”与“最佳”等同起来。我可能读错了你的问题,但似乎你认为更短的实现是自动优越的——对于“优越”的一些定义。

标签: string elixir


【解决方案1】:

不是更短,而是另一种选择:

"Hello world" |> String.graphemes |> Enum.count(& &1 == "o")

感谢@mudasobwa 的惯用方式。

【讨论】:

  • 在惯用的 Elixir 中,"Hello world" |> String.graphemes() |> Enum.count(& &1 == "o") :)
【解决方案2】:

另一种解决方案是将字符串按给定的子字符串拆分,然后返回列表长度减一

len = "foo bar foobar" |> String.split("foo") |> length()
total = len - 1

【讨论】:

    猜你喜欢
    • 2019-10-03
    • 2020-02-21
    • 2012-02-12
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多