From Erlang Community
You have a string made up of multiple lines, and you need to build a string, adding or removing spaces so that all lines are indented equally.
reindent(Str, Num_spaces) -> Lmargin = string:chars($ , Num_spaces), Str_set = string:tokens(Str, "\n"), lists:flatmap( fun(X) -> Lmargin ++ string:strip(X,left) ++ "\n" end, Str_set).
The following examples illustrate the reindention of text, including cases where more space is already provided on the line than desired:
1> io:fwrite("~s", [reindent("one\ntwo\nthree", 3)]). one two three 2> io:fwrite("~s", [reindent("one\n two\n three", 3)]). one two three
This definition uses string:tokens to split the string argument on newliness, then uses lists:flatmap to process each line, removing any existing leading space, prepending the proper indentation to the start of each line, and appending the newline (lost during the tokenization step).