>, and it should return <<"Some">. How can i do it without split function, only b..." /> >, and it should return <<"Some">. How can i do it without split function, only b..." /> >, and it should return <<"Some">. How can i do it without split function, only b..."/>

First word of binary string erlang

460 views Asked by At

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.

2

There are 2 answers

1
Hynek -Pichi- Vychodil On BEST ANSWER

Although Attic's approach is correct, there is a straightforward solution (including trimming of leading spaces):

first_word_bin(Bin) ->
    first_word_bin(ltrim(Bin), <<>>).

first_word_bin(<<>>, Acc) -> Acc;
first_word_bin(<<$\s, _/binary>>, Acc) -> Acc;
first_word_bin(<<X, Bin/binary>>, Acc) ->
    first_word_bin(Bin, <<Acc/binary, X>>).

ltrim(<<$\s, Bin/binary>>) -> ltrim(Bin);
ltrim(Bin) -> Bin.
0
AudioBubble On

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.