String indexing

Be careful when indexing into strings:

julia> s = "αβγδϵhelloω"
"αβγδϵhelloω"

julia> s[end-10:end]
ERROR: StringIndexError("αβγδϵhelloω", 6)
Stacktrace:
 [1] string_index_err(::String, ::Int64) at ./strings/string.jl:12
 [2] getindex(::String, ::UnitRange{Int64}) at ./strings/string.jl:249
 [3] top-level scope at REPL[110]:1

This won’t work because indices work differently for strings:

julia> s[1]
'α': Unicode U+03B1 (category Ll: Letter, lowercase)

julia> s[2]
ERROR: StringIndexError("αβγδϵhelloω", 2)
Stacktrace:
 [1] string_index_err(::String, ::Int64) at ./strings/string.jl:12
 [2] getindex_continued(::String, ::Int64, ::UInt32) at ./strings/string.jl:220
 [3] getindex(::String, ::Int64) at ./strings/string.jl:213
 [4] top-level scope at REPL[114]:1

I’m not completely confident about this code, but you could try

julia> foo(str, n) = chop(str; head=max(0, length(str)-n), tail=0)

julia> foo("name", 7)
"name"

julia> foo("nameforname", 7)
"forname"

julia> foo("αβγδϵhelloω", 7)
"ϵhelloω"

If you want to use indexing in particular, you should look into the prevind and nextind functions:

julia> bar(str, n) = str[prevind(str, lastindex(str), min(length(str), n)-1):end]

julia> bar("name", 7)
"name"

julia> bar("nameforname", 7)
"forname"

julia> bar("αβγδϵhelloω", 7)
"ϵhelloω"
2 Likes