Getting count of occurrences for X in string

Adding an answer to this which allows for interpolation:

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

Actually, this solution breaks for some simple cases due to use of Regex. Instead one might find this useful:

"""
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

What about regexp ?

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

I think that right now the closest built-in thing to what you're after is the length of a split (minus 1). But it's not difficult to specifically create what you're after.

I could see a searchall being generally useful in Julia's Base, similar to matchall. If you don't care about the actual indices, you could just use a counter instead of growing the idxs array.

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

Julia-1.0 update:

For single-character count within a string (in general, any single-item count within an iterable), one can use Julia's count function:

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

(The first argument is a predicate that returns a ::Bool).

For the given example, the following one-liner should do:

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

Julia-1.7 update:

Starting with Julia-1.7 Base.Fix2 can be used, through ==('f') below, as to shorten and sweeten the syntax:

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

Tags:

Julia