How do I get a substring of a string in Julia?

Viewed 1043

Is there a way in Julia that gets from one particular character to another? For example, I want to get the variable s="Hello, world" of 3 to 9 characters.

# output = 'llo, wo'
2 Answers

The other solution is working for ASCII only strings. However, Julia uses byte indexing not character indexing in getindex syntax, as I have discussed on my blog some time ago. If you want to use character indexing (which I assume you do from the wording of your question) here you have a solution using macros.

In general (without using the solution linked above) the functions to use are: chop, first, last, or for index manipulation prevind, nextind, and length.

So e.g. to get characters from 3 to 9 a safe syntaxes are e.g. (just showing several combinations)

julia> str = " Hello! "
" Hello! "

julia> last(first(str, 9), 7)
"Hello! "

julia> chop(str, head=2, tail=length(str)-9)
"Hello! "

julia> chop(first(str, 9), head=2, tail=0)
"Hello! "

julia> str[(:)(nextind.(str, 0, (3, 9))...)]
"Hello! "

Note though that the following is incorrect:

julia> str[3:9]
ERROR: StringIndexError: invalid index [3], valid nearby indices [1]=>'', [5]=>' '

There is an open issue to make chop more flexible which would simplify your specific indexing case.

You can use the following method:

s="Hello, world"

s[3:9]
# output: llo, wo

s[3:end]
# output: llo, world
Related