Skip to content

Commit e94007e

Browse files
Merge pull request #18339 from TotalVerb/fw/split
Make `chop` and `chomp` return `SubString`
2 parents 75bae33 + 4448e57 commit e94007e

File tree

3 files changed

+19
-11
lines changed

3 files changed

+19
-11
lines changed

base/strings/util.jl

+15-9
Original file line numberDiff line numberDiff line change
@@ -58,21 +58,20 @@ startswith(a::Vector{UInt8}, b::Vector{UInt8}) =
5858

5959
# TODO: fast endswith
6060

61-
6261
"""
6362
chop(s::AbstractString)
6463
6564
Remove the last character from `s`.
6665
6766
```jldoctest
68-
julia> a = string("March")
67+
julia> a = "March"
6968
"March"
7069
7170
julia> chop(a)
7271
"Marc"
7372
```
7473
"""
75-
chop(s::AbstractString) = s[1:end-1]
74+
chop(s::AbstractString) = SubString(s, 1, endof(s)-1)
7675

7776
"""
7877
chomp(s::AbstractString)
@@ -81,14 +80,21 @@ Remove a single trailing newline from a string.
8180
"""
8281
function chomp(s::AbstractString)
8382
i = endof(s)
84-
if (i < 1 || s[i] != '\n') return s end
83+
if (i < 1 || s[i] != '\n') return SubString(s, 1, i) end
8584
j = prevind(s,i)
86-
if (j < 1 || s[j] != '\r') return s[1:i-1] end
87-
return s[1:j-1]
85+
if (j < 1 || s[j] != '\r') return SubString(s, 1, i-1) end
86+
return SubString(s, 1, j-1)
87+
end
88+
function chomp(s::String)
89+
i = endof(s)
90+
if i < 1 || s.data[i] != 0x0a
91+
SubString(s, 1, i)
92+
elseif i < 2 || s.data[i-1] != 0x0d
93+
SubString(s, 1, i-1)
94+
else
95+
SubString(s, 1, i-2)
96+
end
8897
end
89-
chomp(s::String) =
90-
(endof(s) < 1 || s.data[end] != 0x0a) ? s :
91-
(endof(s) < 2 || s.data[end-1] != 0x0d) ? s[1:end-1] : s[1:end-2]
9298

9399
# NOTE: use with caution -- breaks the immutable string convention!
94100
function chomp!(s::String)

doc/stdlib/strings.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@
450450

451451
.. doctest::
452452

453-
julia> a = string("March")
453+
julia> a = "March"
454454
"March"
455455

456456
julia> chop(a)

test/strings/util.jl

+3-1
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,9 @@ end
210210

211211
# chomp/chop
212212
@test chomp("foo\n") == "foo"
213-
@test chop("foob") == "foo"
213+
@test chop("fooε") == "foo"
214+
@test isa(chomp("foo"), SubString)
215+
@test isa(chop("foo"), SubString)
214216

215217
# bytes2hex and hex2bytes
216218
hex_str = "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"

0 commit comments

Comments
 (0)