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

string division: "pre"\"prefix" => "fix", "suffix"/"fix" => "suf". #13411

Closed
wants to merge 1 commit into from
Closed
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
29 changes: 28 additions & 1 deletion base/strings/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,34 @@ startswith(a::ByteString, b::ByteString) = startswith(a.data, b.data)
startswith(a::Vector{UInt8}, b::Vector{UInt8}) =
(length(a) >= length(b) && ccall(:strncmp, Int32, (Ptr{UInt8}, Ptr{UInt8}, UInt), a, b, length(b)) == 0)

# TODO: fast endswith
function \(a::AbstractString, b::AbstractString)
i = start(a)
j = start(b)
while !done(a,i) && !done(b,i)
c, i = next(a,i)
d, j = next(b,j)
c == d || @goto non_prefix
end
done(a,i) && return b[j:end]
@label non_prefix
throw(ArgumentError("string division: $(repr(b)) does not start with $(repr(a))"))
end

function /(a::AbstractString, b::AbstractString)
i = endof(a)
j = endof(b)
a1 = start(a)
b1 = start(b)
while a1 <= i && b1 <= j
c = a[i]
d = b[j]
c == d || break
i = prevind(a,i)
j = prevind(b,j)
end
j < b1 && return a[a1:i]
throw(ArgumentError("string division: $(repr(a)) does not end with $(repr(b))"))
end

chop(s::AbstractString) = s[1:end-1]

Expand Down
13 changes: 13 additions & 0 deletions test/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@
@test !endswith("abcd", "dc")
@test !endswith("cd", "abcd")

for a = ("","abc","∀β"), b = ("","abc","∀β")
ab = a*b
@test ab/b == a
@test a\ab == b
end

@test_throws ArgumentError ""/"x"
@test_throws ArgumentError "abc"/"x"
@test_throws ArgumentError "abc"/"abcd"
@test_throws ArgumentError "x"\""
@test_throws ArgumentError "x"\"abc"
@test_throws ArgumentError "abcd"\"abc"

@test filter(x -> x ∈ ['f', 'o'], "foobar") == "foo"

# string iteration, and issue #1454
Expand Down