Does Julia have a string 'contains' substring method?

Julia has a couple of helpful functions that will let you do what a traditional 'contains' function would do.

occursin() takes two arguments. The first of which is the substring you are looking for and the second being the target or string you will be searching in.

findfirst() takes the same arguments but this time returns the index of the first occurrence of the substring if it's found.

julia> a = "HelloWorld"
"HelloWorld"

julia> occursin("Hello", a)
true

julia> findfirst("Hello", a)
1:5

See the Julia docs here for more reading on findfirst() or here for occursin().


While there isn't (at my knowledge) a Julia function to return the index of all the occurrences, it is easy to make one using findnext:

julia> import Base.findall
julia> function findall(pattern,string::AbstractString)
    toReturn = UnitRange{Int64}[]
    s = 1
    while true
        range = findnext(pattern,string,s)
        if range == nothing
             break
        else
            push!(toReturn, range)
            s = first(range)+1
        end
    end
    return toReturn
end

julia> st = "Today is a fresh day: not too warm, not to cold, just fresh!"
"Today is a fresh day: not too warm, not to cold, just fresh!"
julia> ranges = findall("fresh",st)
2-element Array{UnitRange{Int64},1}:
 12:16
 55:59
julia> st2 = "aaffssffssffbbffssffcc"
"aaffssffssffbbffssffcc"
julia> ranges = findall("ffssff",st2)
3-element Array{UnitRange{Int64},1}:
 3:8  
 7:12 
 15:20
julia> ranges = findall("zz",st2)
0-element Array{UnitRange{Int64},1}

Replace s = first(range)+1 with s = last(range)+1 if you want to account only for full independent patterns.

Tags:

String

Julia