Erlang Central

Difference between revisions of "String Indent"

From ErlangCentral Wiki

(fix an error in the solution: it strips too much whitespace)
(One intermediate revision by one user not shown)
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>
Line 29:Line 29:
 
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).
 
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).
  
[[Category:CookBook]]
+
[[Category:CookBook]][[Category:StringRecipes]]

Revision as of 19:06, 24 September 2006

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.

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