> Erlang中文手册 > strip/3 去除字符串两边的字符

string:strip/3

去除字符串两边的字符

用法:

strip(String, Direction, Character) -> Stripped

内部实现:

-spec strip(String, Direction, Character) -> Stripped when
      String :: string(),
      Stripped :: string(),
      Direction :: left | right | both,
      Character :: char().

strip(String, right, Char) -> strip_right(String, Char);
strip(String, left, Char) -> strip_left(String, Char);
strip(String, both, Char) ->
    strip_right(strip_left(String, Char), Char).

strip_left([Sc|S], Sc) ->
    strip_left(S, Sc);
strip_left([_|_]=S, Sc) when is_integer(Sc) -> S;
strip_left([], Sc) when is_integer(Sc) -> [].

strip_right([Sc|S], Sc) ->
    case strip_right(S, Sc) of
	[] -> [];
	T  -> [Sc|T]
    end;
strip_right([C|S], Sc) ->
    [C|strip_right(S, Sc)];
strip_right([], Sc) when is_integer(Sc) ->
    [].

去除字符串 String 左/右边的字符 Character,参数 Direction 标明要去除哪边的空格,left 表示只去除左边,right 表示只去除右边,both 表示两边都去除

string:strip("...abcdefg...", both, $.).
string:strip("...abcdefg...", left, $.).
string:strip("...abcdefg.,,", right, $,).