Skip to content

Commit

Permalink
allow nchar to be geater than string length in first/last without thr…
Browse files Browse the repository at this point in the history
…owing an error
  • Loading branch information
bkamins committed Nov 9, 2017
1 parent 27665e8 commit fc7573c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
19 changes: 14 additions & 5 deletions base/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -595,7 +595,7 @@ end
"""
first(str::AbstractString, nchar::Integer)
Get a string consisting of the first `nchar` characters of `str`.
Get a string consisting of at most the first `nchar` characters of `str`.
```jldoctest
julia> first("∀ϵ≠0: ϵ²>0", 0)
Expand All @@ -606,19 +606,24 @@ julia> first("∀ϵ≠0: ϵ²>0", 1)
julia> first("∀ϵ≠0: ϵ²>0", 3)
"∀ϵ≠"
julia> first("1234", 10)
"1234"
```
"""
function first(str::AbstractString, nchar::Integer)
s = start(s)
if 0 <= nchar <= 1
return str[1:nchar]
return str[s:(s-1+nchar)]
end
str[1:nextind(str, 1, nchar-1)]
idx = min(endof(str), nextind(str, s, nchar-1))
str[s:idx]
end

"""
last(str::AbstractString, nchar::Integer)
Get a string consisting of the last `nchar` characters of `str`.
Get a string consisting of at most the last `nchar` characters of `str`.
```jldoctest
julia> last("∀ϵ≠0: ϵ²>0", 0)
Expand All @@ -629,14 +634,18 @@ julia> last("∀ϵ≠0: ϵ²>0", 1)
julia> last("∀ϵ≠0: ϵ²>0", 3)
"²>0"
julia> last("1234", 10)
"1234"
```
"""
function last(str::AbstractString, nchar::Integer)
e = endof(str)
if 0 <= nchar <= 1
return str[(e-nchar+1):e]
end
str[prevind(str, e, nchar-1):e]
idx = max(start(str), prevind(str, e, nchar-1))
str[idx:e]
end

# reverse-order iteration for strings and indices thereof
Expand Down
4 changes: 2 additions & 2 deletions test/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -645,15 +645,15 @@ end
@test first(s, 3) == "∀ϵ≠"
@test first(s, 4) == "∀ϵ≠0"
@test first(s, length(s)) == s
@test_throws BoundsError first(s, length(s)+1)
@test first(s, length(s)+1) == s
@test_throws ArgumentError last(s, -1)
@test last(s, 0) == ""
@test last(s, 1) == "0"
@test last(s, 2) == ">0"
@test last(s, 3) == "²>0"
@test last(s, 4) == "ϵ²>0"
@test last(s, length(s)) == s
@test_throws BoundsError last(s, length(s)+1)
@test last(s, length(s)+1) == s
end

@testset "invalid code point" begin
Expand Down

0 comments on commit fc7573c

Please sign in to comment.