erlang:字符串剥离多个字符

erlang: string strip multiple characters

我看到 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,此版本以最小化堆使用的方式编写。

以下函数获取从字符串 S 中删除的字符列表 L 将实现您的 objective:

stripm(S, both, L) -> S1 = stripm(S,L),
    lists:reverse(stripm(lists:reverse(S1),L)).

stripm([], _L) -> [];
stripm(S = [H|T], L) ->
    case lists:member(H, L) of
        true -> 
            S1 = string:strip(T,left,H),
            stripm(S1, L);
        false ->
            S
    end.