获取字符串中 X 出现的次数

问题描述 投票:0回答:8

我正在寻找像Python这样的函数

"foobar, bar, foo".count("foo")

找不到任何似乎能够以明显的方式执行此操作的函数。寻找单一功能或不完全矫枉过正的东西。

julia
8个回答
14
投票

Julia-1.0
更新:

对于字符串中的单字符计数(一般来说,可迭代中的任何单项计数),可以使用 Julia 的

count
函数:

julia> count(i->(i=='f'), "foobar, bar, foo")
2

(第一个参数是返回 ::Bool 的谓词)。

对于给定的示例,应执行以下一行操作:

julia> length(collect(eachmatch(r"foo", "bar foo baz foo")))
2

Julia-1.7
更新:

可以使用从

Julia-1.7
Base.Fix2
开始,通过下面的
==('f')
,来缩短和美化语法:

julia> count(==('f'), "foobar, bar, foo")
2

11
投票

正则表达式怎么样?

julia> length(matchall(r"ba", "foobar, bar, foo"))
2

9
投票

现在只是

count
:

julia> count("foo", "foobar, bar, foo")
2

2
投票

添加一个允许插值的答案:

julia> a = ", , ,";
julia> b = ",";
julia> length(collect(eachmatch(Regex(b), a)))
3

实际上,由于使用正则表达式,该解决方案在某些简单情况下会失败。相反,人们可能会发现这很有用:

"""
count_flags(s::String, flag::String)

counts the number of flags `flag` in string `s`.
"""
function count_flags(s::String, flag::String)
counter = 0
for i in 1:length(s)
  if occursin(flag, s)
    s = replace(s, flag=> "", count=1)
    counter+=1
  else
    break
  end
end
return counter
end

1
投票

很抱歉发布另一个答案而不是评论前一个答案,但我还没有设法处理评论中的代码块:)

如果你不喜欢正则表达式,也许可以使用像这样的尾递归函数(按照 Matt 的建议使用 search() 基本函数):

function mycount(what::String, where::String)
  function mycountacc(what::String, where::String, acc::Int)
    res = search(where, what)
    res == 0:-1 ? acc : mycountacc(what, where[last(res) + 1:end], acc + 1)
  end
  what == "" ? 0 : mycountacc(what, where, 0)
end

1
投票

这简单快速(并且不会溢出堆栈):

function mycount2(where::String, what::String)
    numfinds = 0
    starting = 1
    while true
        location = search(where, what, starting)
        isempty(location) && return numfinds
        numfinds += 1
        starting = location.stop + 1
    end
end

1
投票

一行:(Julia 1.3.1):

julia> sum([1 for i = eachmatch(r"foo", "foobar, bar, foo")])
2

1
投票

自 Julia 1.3 起,就有了一个

count
方法可以做到这一点。

  count(
      pattern::Union{AbstractChar,AbstractString,AbstractPattern},
      string::AbstractString;
      overlap::Bool = false,
  )

  Return the number of matches for pattern in string.  
  This is equivalent to calling length(findall(pattern, string)) but more
  efficient.

  If overlap=true, the matching sequences are allowed to overlap indices in the
  original string, otherwise they must be from disjoint character ranges.

  │ Julia 1.3
  │
  │  This method requires at least Julia 1.3.
julia> count("foo", "foobar, bar, foo") 
2

julia> count("ana", "bananarama")
1

julia> count("ana", "bananarama", overlap=true)
2

© www.soinside.com 2019 - 2024. All rights reserved.