[erlang-questions] Smart way to trim a binary?

Philip Robinson <>
Wed Jun 24 12:14:15 CEST 2009


Two versions that avoid converting to a list:

trim(Bin= <<C,BinTail/binary>>) ->
    case is_whitespace(C) of
        true -> trim(BinTail);
        false -> trim_tail(Bin)
    end.

trim_tail(<<C>>) ->
    case is_whitespace(C) of
        true -> false;
        false -> <<C>>
    end;
trim_tail(<<C,Bin/binary>>) ->
    case trim_tail(Bin) of
        false -> trim_tail(<<C>>);
        BinTail -> <<C,BinTail/binary>>
    end.

% Another version of the above.
trim2(Bin= <<C,BinTail/binary>>) ->
    case is_whitespace(C) of
        true -> trim2(BinTail);
        false -> trim_tail2(Bin)
    end.

trim_tail2(<<>>) -> <<>>;
trim_tail2(Bin) ->
    Size = size(Bin) - 1,
    <<BinHead:Size/binary,C>> = Bin,
    case is_whitespace(C) of
        true -> trim_tail2(BinHead);
        false -> Bin
    end.

is_whitespace($\s) -> true;
is_whitespace($\t) -> true;
is_whitespace($\n) -> true;
is_whitespace($\r) -> true;
is_whitespace(_) -> false.


I am not so sure that either of these are "smarter" or "nicer", though...

Cheers,
Philip


On Wed, Jun 24, 2009 at 10:21 AM, Steve
Davis<> wrote:
> I have this feeling that there's a much smarter way to trim a string
> presented as a binary rather than this (mostly found in couch_util)...
>
> trim(Bin) when is_binary(Bin) ->
>        list_to_binary(trim(binary_to_list(Bin)));
> trim(String) when is_list(String) ->
>    String2 = lists:dropwhile(fun is_whitespace/1, String),
>    lists:reverse(lists:dropwhile(fun is_whitespace/1, lists:reverse
> (String2))).
>
> is_whitespace($\s)-> true;
> is_whitespace($\t)-> true;
> is_whitespace($\n)-> true;
> is_whitespace($\r)-> true;
> is_whitespace(_Else) -> false.
>
> ...anybody have a nice way of doing this?
>
> TIA & BR,
> /sd
>
> ________________________________________________________________
> erlang-questions mailing list. See http://www.erlang.org/faq.html
> erlang-questions (at) erlang.org
>
>


More information about the erlang-questions mailing list