我希望在 Erlang 的字符串中的特定位置处插入字符。
例如即可。假设我希望在位置3,5,7的字符串“123456789”中插入“,”。
123456789 ~> 12,34,56,789
任何帮助欣赏!!谢谢:))
答案 0 :(得分:2)
取而代之的是作为完成的解决方案回答我展示了你自己如何轻松找到它。
一个。定义输入数据 - 用于转换的Str字符串,Pos - 列表,其中包含插入位置。
simple_transform(Str,Positions)->
B中。部分解决问题。我们需要的?使用获取元素和索引迭代列表,将函数应用于它们并检测列表中的元素。这就是全部。如果您需要使用列表,通常会使用标准库中的模块列表。查看documentation并寻找合适的功能。
收集所有内容:
simple_transform(Str,Positions)->
{List,_}=lists:mapfoldl(
fun(El,Acc)->case lists:member(Acc,Positions) of
true ->{[$,,El],Acc+1};
false ->{El,Acc+1} end end,1,Str),
lists:flatten(List).
答案 1 :(得分:1)
以下解决方案要求将职位列表从低到高排序:
1)插入单个字符串:
insert_test() ->
"a,b" = insert(",", "ab", [2]),
",a" = insert(",", "a", [1]),
"ab" = insert(",", "ab", [3]),
"a,b,c" = insert(",", "abc", [2,3]),
all_tests_passed.
insert([InsertChar], String, Positions) ->
insert(InsertChar, String, Positions, 1, []).
insert(InsertChar, [Char|Chars], [Index|Ps], Index, Acc) ->
insert(InsertChar, Chars, Ps, Index+1, [Char,InsertChar|Acc]);
insert(InsertChar, [Char|Chars], Ps, Index, Acc) ->
insert(InsertChar, Chars, Ps, Index+1, [Char|Acc] );
insert(_, [], _, _, Acc) ->
lists:reverse(Acc).
2)插入随机长度字符串:
insert_test() ->
"a,b" = insert(",", "ab", [2]),
",a" = insert(",", "a", [1]),
"a--b" = insert("--", "ab", [2]),
"--ab" = insert("--", "ab", [1]),
"a--b--c" = insert("--", "abc", [2,3]),
all_tests_passed.
insert(InsertStr, Str, Positions) ->
insert(InsertStr, Str, Positions, 1, []).
insert(InsertStr, [Char|Chars], [Index|Ps], Index, Acc) ->
insert(InsertStr, Chars, Ps, Index+1, combine(InsertStr, Char, Acc) );
insert(InsertStr, [Char|Chars], Ps, Index, Acc) ->
insert(InsertStr, Chars, Ps, Index+1, [Char|Acc]);
insert(_, [], _, Acc, _) ->
lists:reverse(Acc).
combine_test() ->
",X" = lists:reverse( combine(",", $X, []) ),
"a,X" = lists:reverse( combine(",", $X, "a") ),
"ab--X" = lists:reverse( combine("--", $X, lists:reverse("ab") ) ),
all_tests_passed.
combine([], X, Acc) ->
[X|Acc];
combine([Char|Chars], X, Acc) ->
combine(Chars, X, [Char|Acc]).
答案 2 :(得分:0)
如果您希望将字符串转换为非常特定的格式:
insert_commas(String) ->
string:join([string:substr(String, 1, 2), ",", string:substr(String, 3, 2), ",", string:substr(String, 5, 2), ",", string:substr(String, 7)], "").
module:insert_commas("123456789").` returns `"12,34,56,789"