我看到erlang有string:strip
方法,您也可以在第三个参数上指定要去除的字符:
string:strip("...Hello.....", both, $.).
但是,如何定义多个要剥离的字符?所以例如如果我有的话,".;.;..Hello...;.."
我想把它剥离到"Hello"
。
编写strip/3
带有剥离字符支持列表的自己的版本并不像看起来那样困难:
strip(S, left, Ds) ->
lstrip(S, Ds);
strip(S, right, Ds) ->
rstrip(S, Ds);
strip(S, both, Ds) ->
rstrip(lstrip(S, Ds), Ds).
lstrip([], _) -> [];
lstrip([H|T] = S, Ds) ->
case lists:member(H, Ds) of
true -> lstrip(T, Ds);
false -> S
end.
rstrip([], _) -> [];
rstrip([H|T], Ds) ->
case rstrip(T, Ds) of
[] ->
case lists:member(H, Ds) of
true -> [];
false -> [H]
end;
S -> [H|S]
end.
注意lists:member/2
是BIF,此版本的编写方式可最大程度地减少堆的使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句