s c h e m a t i c s : c o o k b o o k

/ StringChapter / Cookbook.StringIndent

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

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

(require (lib "string.ss" "srfi" "13"))
(define (reindent s num-spaces)
  (let ((lmargin (make-string num-spaces #\space))
        (newline (make-string 1 #\newline)))
    (string-join (map (lambda (a-line) 
                        (string-append lmargin (string-trim a-line))) 
                      (string-tokenize s)) 
                 newline)))

> (display (reindent "one\ntwo\nthree" 3))
   one
   two
   three
> (display (reindent "one\n     two\n  three" 3))
   one
   two
   three

Discussion

This definition uses string-tokenize to split the string argument on newliness, then uses map to process each line, removing any existing leading space and then appending the proper indentation to the start of each line. Finally, the result of map is passed to string-join, which joins the result with newlines.

-- GordonWeakliem - 26 Apr 2004

CookbookForm
TopicType: Recipe
ParentTopic: StringRecipes
TopicOrder: 130

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, 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