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

Chandru <>
Wed Jun 24 11:04:52 CEST 2009


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)].

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