I’m curious if there is a better way to remove the first and last character of a given string using pattern matching.
Basically, if an initial string is - "hello", my function should output - "ello".
My very quick implementation is:
def remove_letters(<<_::binary-size(1)>> <> tail) do
length = byte_size(tail)
<<result::binary-size(length - 1), ext::binary>> = tail
result
end
It works, but I’m curious if there is a way I can use a smarter pattern-matching approach in the function head to avoid extra steps in the function body?!
I think your code would return ell since it removes both first and last bytes? One small note - your code only works on single-byte characters (not UTF-8).
On more recent OTP versions you can also do:
def remove_first_and_last(string) do
<<_first::binary-1,mid::binary-size(byte_size(string) - 2),_last::binary-1>> = string
mid
end
@outlog@simonrobins
Yeah, I’m pretty aware of those approaches.
I was specifically curious about string pattern matching!
Thank you though! I appreciate it!
@kip
Yes!!! Exactly what I was curious about!
I knew it was possible!
Adding it to my knowledge library
Thank you so much! Really really appreciate it!