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

Chandru <>
Wed Jun 24 11:41:11 CEST 2009


2009/6/24 Chandru <>

> trim(Bin) when is_binary(Bin) ->
>     << << X >> || <<X>> <= Bin, not is_whitespace(X) >>;
> trim(Str) when is_list(Str) ->
>    [X || X <- Str, not is_whitespace(X)].
>

Oops! Was a bit too quick there. I guess the function is actually trying to
duplicate the behaviour of string:strip/1 but expanding to include all kinds
of whitespace.

Here is one which works as expected:

trim(Bin) when is_binary(Bin) ->
    trim_1(trim_1(Bin));
trim(Str) when is_list(Str) ->
   trim_1(trim_1(Str)).

trim_1(Bin) when is_binary(Bin) ->
    trim_1(Bin, drop, <<>>);
trim_1(Str) when is_list(Str) ->
    trim_1(Str, drop, []).

trim_1(<<>>, _, Acc) -> Acc;
trim_1([], _, Acc)   -> Acc;
trim_1(<<X, Rest/binary>>, keep, Acc) ->
    trim_1(Rest, keep, <<X, Acc/binary>>);
trim_1([X | Rest], keep, Acc) ->
    trim_1(Rest, keep, [X | Acc]);
trim_1(<<X, Rest/binary>>, drop, Acc) ->
    case is_whitespace(X) of
    true ->
        trim_1(Rest, drop, Acc);
    false ->
        trim_1(Rest, keep, <<X, Acc/binary>>)
    end;
trim_1([X | Rest], drop, Acc) ->
    case is_whitespace(X) of
    true ->
        trim_1(Rest, drop, Acc);
    false ->
        trim_1(Rest, keep, [X | Acc])
    end.

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




>
> cheers
> Chandru
>
> 2009/6/24 Steve Davis <>
>
> 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