Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any better way to get first n bytes, and the rest of a String? Currently using binary_part and String.trim_leading

Tags:

elixir

Given a string str = "üabc123", and size = 5. I want to get the first 5 bytes("üabc"), and the rest of the string("123").

Currently I'm doing:

str = "üabc123"
size = 5
a = binary_part(str, 0, size)      # "üabc"
b = String.trim_leading(str, a)    # "123"

Seems like there would be a cleaner way to do this. Is there another way?

like image 893
Peter R Avatar asked Jan 27 '23 05:01

Peter R


1 Answers

You can use binary pattern matching

<< a::binary-size(5), b::binary >> = "üabc123"
a == "üabc"
b == "123"
like image 140
Justin Wood Avatar answered May 31 '23 22:05

Justin Wood