> Erlang中文手册 > substr/3 截取字符串

string:substr/3

截取字符串

用法:

substr(String, Start, Length) -> Substring

从字符串 String 里截取一个从 Start 位置开始,长度是 Length 的子字符串 Substring。

string:substr("abcdefg", 3, 2).

Erlang 版实现的全排列:

Str = "abc",
Len = length(Str),
StrToListFun = fun(Start, AccList) ->
    Element = string:substr(Str, Start, 1),
    [Element | AccList]
end,
StringList = lists:foldr(StrToListFun, [], lists:seq(1, Len)),
NormalizeFun = fun
    Normalize([], _N, _I, R) ->
        lists:reverse(R);
    Normalize([H | L], I, I, R) ->
        [H] ++ lists:reverse(R) ++ L;
    Normalize([H | L], N, I, R) ->
        Normalize(L, N + 1, I, [H | R])
end,
PermutationFun = fun PermutationFun(N, [StrList, HeadList, Ret]) ->
    NewStrList = NormalizeFun(StrList, 1, N, []),
    iostrList = HeadList ++ NewStrList,
    NewRet = [string:join(IOStrList, "") | Ret],
    if
        length(NewStrList) > 1 ->
            [Item | AccStrList] = NewStrList,
            AccLen = length(AccStrList),
            NewHeadList = HeadList ++ [Item],
            [_SL, _HL, PermutationLoopRet] = lists:foldr(PermutationFun, [AccStrList, NewHeadList, []], lists:seq(2, AccLen)),
            [StrList, HeadList, PermutationLoopRet ++ NewRet];
        true ->
            [StrList, HeadList, NewRet]
    end
end,
[_StrList, _HeadList, RetList] = lists:foldr(PermutationFun, [StringList, [], []], lists:seq(1, Len)),
RetList.