String Indent

From Erlang Community

(Difference between revisions)
Revision as of 21:52, 3 September 2006 (edit)
Bfulgham (Talk | contribs)

← Previous diff
Current revision (19:06, 24 September 2006) (edit) (undo)
Ayrnieu (Talk | contribs)
(fix an error in the solution: it strips too much whitespace)
 
Line 10: Line 10:
lists:flatmap( lists:flatmap(
fun(X) -> fun(X) ->
- Lmargin ++ string:strip(X) ++ "\n"+ Lmargin ++ string:strip(X,left) ++ "\n"
end, Str_set). end, Str_set).
</code> </code>

Current revision

[edit] Problem

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.

[edit] Solution

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

Erlang/OTP Projects
Personal tools