Why does Base.rsplit not invert the order (compared to Base.split) of the data in Julia?

Viewed 70

I am trying out Base.rsplit() for the first time and I was surprised to see that the order of the data does not change when I use split vs rsplit. See this example:

julia> my_string = "Hello.World.This.Is.A.Test"
"Hello.World.This.Is.A.Test"

julia> a = split(my_string, ".")
6-element Vector{SubString{String}}:
 "Hello"
 "World"
 "This"
 "Is"
 "A"
 "Test"

julia> b = rsplit(my_string, ".")
6-element Vector{SubString{String}}:
 "Hello"
 "World"
 "This"
 "Is"
 "A"
 "Test"

julia> a == b
true

This is a bit counterintuitive given that rsplit says:

Similar to split, but starting from the end of the string.

1 Answers

rsplit just goes from the right side and the only practical difference is the limit parameter.

Try typing in Julia:

@less rsplit("txt",".")

You will find the following function:

function _rsplit(str::AbstractString, splitter, limit::Integer, keepempty::Bool, strs::Array)
    n = lastindex(str)::Int
    r = something(findlast(splitter, str)::Union{Nothing,Int,UnitRange{Int}}, 0)
    j, k = first(r), last(r)
    while j > 0 && k > 0 && length(strs) != limit-1
        (keepempty || k < n) && pushfirst!(strs, @inbounds SubString(str,nextind(str,k)::Int,n))
        n = prevind(str, j)::Int
        r = something(findprev(splitter,str,n)::Union{Nothing,Int,UnitRange{Int}}, 0)
        j, k = first(r), last(r)
    end
    (keepempty || n > 0) && pushfirst!(strs, SubString(str,1,n))
    return strs
end
Related