Getting count of occurrences for X in string

julia

Solution

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

Problem

Im looking for a function like Pythons ``` "foobar, bar, foo".count("foo") ``` Could not find any functions that seemed able to do this, in a obvious way. Looking for a single function or something that is not completely overkill.

Original source