Skip to content

Commit

Permalink
Add get(string, index, default) (#22500)
Browse files Browse the repository at this point in the history
  • Loading branch information
staticfloat authored and KristofferC committed Jun 26, 2017
1 parent 36379d2 commit 6e93321
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions base/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ getindex(s::AbstractString, v::AbstractVector{<:Integer}) =
getindex(s::AbstractString, v::AbstractVector{Bool}) =
throw(ArgumentError("logical indexing not supported for strings"))

get(s::AbstractString, i::Integer, default) = isvalid(s,i) ? s[i] : default
Symbol(s::AbstractString) = Symbol(String(s))

"""
Expand Down
15 changes: 15 additions & 0 deletions test/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,21 @@ end
@test SubString("", 1, 6)[10:9] == ""
@test SubString("", 1, 0)[10:9] == ""

# issue #22500 (using `get()` to index strings with default returns)
let
utf8_str = "我很喜欢Julia"

# Test that we can index in at valid locations
@test get(utf8_str, 1, 'X') == ''
@test get(utf8_str, 13, 'X') == 'J'

# Test that obviously incorrect locations return the default
@test get(utf8_str, -1, 'X') == 'X'
@test get(utf8_str, 1000, 'X') == 'X'

# Test that indexing into the middle of a character returns the default
@test get(utf8_str, 2, 'X') == 'X'
end

#=
# issue #7764
Expand Down

0 comments on commit 6e93321

Please sign in to comment.