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

Julia 获取字符串中X的出现次数,julia,Julia,我正在寻找像Pythons这样的函数 "foobar, bar, foo".count("foo") 显然,找不到任何似乎能够做到这一点的函数。寻找一个单一的函数或不是完全多余的东西。关于regexp呢 julia> length(matchall(r"ba", "foobar, bar, foo")) 2 我认为现在最接近你所追求的是分割的长度(减去1)。但具体地创造你想要的并不困难 我可以看到一个searchall在Julia的Base中通常很有用,类似于matchall。如果不关

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

"foobar, bar, foo".count("foo")
显然,找不到任何似乎能够做到这一点的函数。寻找一个单一的函数或不是完全多余的东西。

关于regexp呢

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

我认为现在最接近你所追求的是
分割的长度(减去1)。但具体地创造你想要的并不困难

我可以看到一个
searchall
在Julia的Base中通常很有用,类似于
matchall
。如果不关心实际的索引,可以使用计数器,而不是增加
idxs
数组

function searchall(s, t; overlap::Bool=false)
    idxfcn = overlap ? first : last
    r = findnext(s, t, firstindex(t))
    idxs = typeof(r)[] # Or to only count: n = 0
    while r !== nothing
        push!(idxs, r) # n += 1
        r = findnext(s, t, idxfcn(r) + 1)
    end
    idxs # return n
end

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

如果您不喜欢regexp,可以使用下面这样的尾部递归函数(使用Matt建议的search()基函数):

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


Julia-1.0
更新:

对于字符串中的单个字符计数(通常,iterable中的任何单个项计数),可以使用Julia的
count
函数:

julia> count(i->(i=='f'), "foobar, bar, foo")
2
(第一个参数是返回::Bool的谓词)

对于给定的示例,以下一个衬里应该可以:

julia> length(collect(eachmatch(r"foo", "bar foo baz foo")))
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

一行:(Julia 1.3.1):


我不明白朱莉娅的问题和目标C有什么关系?上述问题的解决方案与我所要求的答案也不尽相同。这是我最终得到的一个“理智”的解决方案,但我有点恼人,因为我不得不逃避重复字符(如果你在使用函数时不知道传递的字符串是什么,那真的很恼人)。另外,我觉得用RE来做这样的事情有点过分了,尽管它比手动搜索字符串要好。你可以把这段代码封装在一个函数中来隐藏regexOf,当然会用到一个函数。问题是
julia>matchall(Regex(“Dots”),“Dots is cool”)1元素数组{SubString{UTF8String},1}:“Dots”
(我希望代码标记能起作用)不应该匹配,因为“.”,转义RE字符并不难,但至少在我看来,应该有一个比使用RE更简单的解决方案。我得到了一个
错误:UndefVarError:matchall not defined
。如何定义它?Woops,看起来像是我在拆分时得到的,期望其他输出。这是一个更好的解决方案,没有i don’我同意你的看法。
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
julia> sum([1 for i = eachmatch(r"foo", "foobar, bar, foo")])
2