learn-julia-the-hard-way icon indicating copy to clipboard operation
learn-julia-the-hard-way copied to clipboard

Chapter 5: Strings

Open sbromberger opened this issue 10 years ago • 3 comments
trafficstars

In the interpolation section, you talk about * and $ constructs, and mention that $ is faster than *, but you don't mention that string(...) is fastest of all.

sbromberger avatar Jan 07 '15 03:01 sbromberger

Where a search string is not found, search() will yield 0:-1. That is an odd result, until you realise the reason: for any string s, s[0:-1] will necessarily yield "" (that is, an empty string).

Why is this the case? [1:-1] does the same thing, but [0:0] returns a BoundsError.

sbromberger avatar Jan 07 '15 03:01 sbromberger

s[0,0] means 'give me all characters from the 0th to the 0th. Julia is 1-indexed, so you're asking for a non-existent index, and that's what Julia is trying to get at by the BoundsError.

chrisvoncsefalvay avatar Jan 08 '15 13:01 chrisvoncsefalvay

OK, but that doesn't explain why [0:-1] works. It's "give me all the characters from the 0th to the -1st", which seems even more wrong than [0:0].

Ah, this explains it:

julia> [0:0]
1-element Array{Int64,1}:
 0

julia> [0:-1]
0-element Array{Int64,1}

julia>

sbromberger avatar Jan 08 '15 16:01 sbromberger