Why does the Base.match function return a SubString{String} type rather than just String in Julia?

Viewed 40
julia> s = "abcdefg"
"abcdefg"

julia> s1 = s[3:4]
"cd"

julia> s2 = match(r"c.", s).match
"cd"

julia> typeof(s)
String

julia> typeof(s1)
String

julia> typeof(s2)
SubString{String}

What functionality does SubString enable? It looks like a container. If so, what other types can it hold? If this is useful, why isn't s1 a SubString?

I found this behavior strange when I had to convert s2 into a pure String to get it into a f(x::String) function. What is the difference between using String(s2) and string(s2) for that conversion?

1 Answers

SubString{String} is just a view of String. s1[3:4] is not a SubString because it is getindex not view function (just like with arrays).

  1. It is SubString{String} to avoid copying of data in the string, see e.g.:
julia> using BenchmarkTools

julia> x = "a"^1_000_000;

julia> @btime $x[1:end];
  36.000 μs (1 allocation: 976.69 KiB)

julia> @btime @view $x[1:end];
  23.046 ns (0 allocations: 0 bytes)

to note how much difference in allocations and speed it makes

  1. In general you should avoid writing s[3:4] as it is not a safe indexing code (it is only safe if your string is ASCII which you can check with isascii). String indexing in Julia uses byte indices (not character indices)

  2. SubString{String} has String parameter, as there are in general other string types than only String:

julia> using InlineStrings

julia> x = InlineString("abcd")
"abcd"

julia> typeof(x)
String7

julia> y = @view x[1:end]
"abcd"

julia> typeof(y)
SubString{String7}
  1. As it is noted in comment by Antonello - most likely the f function should accept AbstractString and you would not even notice a problem.

All this is explained in https://docs.julialang.org/en/v1/manual/strings/.

If you want something more hands-on check out for example chapter 6 of https://www.manning.com/books/julia-for-data-analysis (I do not want to do too much self promotion, but your question is one of the standard questions users ask and I explained all these topics in this chapter to address them).

Related