Is there something like Julia rsplit
for Crystal ?
String#rpartition
would be equivalent to rsplit(limit = 2)
.
Without limit, you could call #reverse
on the result of String#split
.
def rsplit(s : String, sep : Char | String, limit : Int32 = 0, remove_empty : Bool = true, & : String ->)
limit = Int32::MAX if limit <= 0
count = 1
offset = s.size - 1
sep_size = sep.is_a?(Char) ? 1 : sep.size
while offset >= 0
off = offset - sep_size + 1
if count < limit && off >= 0 && (index = s.rindex(sep, offset: off))
unless remove_empty && index == off
count += 1
return if (yield s[(index + sep_size)..offset]) == Iterator.stop
end
offset = index - 1
else
yield s[..offset]
return
end
end
end
Maybe it would be better to iterate the characters directly instead of “rindex”
A dedicated implementation like rindex
should technically be more optimized. However, it is not as good as it could be because it returns a character index, so slicing from that is very inefficient. We’re missing an implementation of byte_rindex
to make this really efficient.
Iterating characters would also get ugly it the separator is a string.