现在我一直在使用Regex.scan方法:
Regex.scan(~r/do/i, “Do. Or do not. There is no try.") |> length
Run Code Online (Sandbox Code Playgroud)
在 Ruby 中,我们可以使用.scan方法:"Hello world".count "o" #=> 2
是否有更短的方法来使用 Elixir 计算字符串中的子字符串?不需要花哨的正则表达式,我只需要计算一个字符串中有多少个子字符串。
不是更短,而是另一种选择:
"Hello world" |> String.graphemes |> Enum.count(& &1 == "o")
Run Code Online (Sandbox Code Playgroud)
感谢@mudasobwa 的惯用方式。
另一种解决方案是按给定的子字符串拆分字符串,然后返回列表长度减一
len = "foo bar foobar" |> String.split("foo") |> length()
total = len - 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1998 次 |
| 最近记录: |