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

Viewed 623

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?

2 Answers

You can use binary pattern matching

<< a::binary-size(5), b::binary >> = "üabc123"
a == "üabc"
b == "123"

Here is a oneline split, just out of curiosity:

# make sure u-umlaut is combined diacritical
[lead, trail] =
  str
  |> to_charlist() 
  |> Enum.split(size)
  |> Tuple.to_list()
  |> Enum.map(&to_string/1)
#⇒ ["üabc", "123"]
Related