chrisvoncsefalvay / learn-julia-the-hard-way

Learn Julia the hard way!
https://app.gitbook.com/@chrisvoncsefalvay/s/learn-julia-the-hard-way/
Other
772 stars 153 forks source link

Chapter 5: Strings #21

Open sbromberger opened 9 years ago

sbromberger commented 9 years ago

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 commented 9 years ago
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.

chrisvoncsefalvay commented 9 years ago

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.

sbromberger commented 9 years ago

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>