Search code examples
erlangnumber-formatting

Insert Char at specific position in string Erlang


I wish to insert a character at a specific position in the string in Erlang.

Eg. Suppose i wish to insert "," in string "123456789" at position 3,5,7.

123456789 ~> 12,34,56,789

Any help Appreciated!! Thanks :)


Solution

  • The following solutions require that the positions list be sorted low to high:

    1) To insert a single character string:

    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) To insert a random length string:

    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]).