I need to do something like this <<"Some text in binary">>, and it should return <<"Some">. How can i do it without split function, only by pattern matching and select/if cases with Erlang. Thank you.
First word of binary string erlang
519 views Asked by user2513522 AtThere are 2 answers
Not sure why you wouldn't want to use binary:split. Here's one method of achieving this, but I don't really like it.
first_word_bin(Bin) ->
Len = length_till_space(Bin, 0),
<<Bin:Len/binary>>.
length_till_space(<<>>, Num) -> Num;
length_till_space(<<$\s, _/binary>>, Num) -> Num;
length_till_space(<<_:1/binary, Tl/binary>>, Num) ->
length_till_space(Tl, Num + 1).
However if the binary has a space at the beginning e.g.
<<" Some text in binary">>
then the result will be <<>>, without the space at the start it will be <<"Some">>. This could be fixed by trimming the starting whitespace beforehand but you could use the same method.
So we use length_till_space to get the amount of characters until it hits a space. First case checks if binary is empty, second case checks if the head of the binary is $\s (space) and last case just does a tail call and increments the number.
Then lastly we just get the first X amount of characters from the binary and return that.
Although Attic's approach is correct, there is a straightforward solution (including trimming of leading spaces):