Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add get(string, index, default) #22500

Merged
merged 1 commit into from
Jun 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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