e r l a n g : c o o k b o o k

/ Erlang.StringIndent

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Changing the Indentation of a String

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) ++ "\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

Discussion

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

Contributors

Based on work by GordonWeakliem and NoelWelsh.

-- BrentAFulgham - 21 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: StringRecipes
TopicOrder: 130

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest