Groovy String.indent
Adjust each line’s indentation and normalize line endings to LF.
A simple example
String.indent
- Start with "A" on one line
- Do this Indent by two spaces
- Result Two spaces, A, newline
Syntax
public String indent(int n)
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyIndent a printed checklist
A plain-text printer needs to set a checklist apart from its surrounding notice. Add a consistent left margin to each item and inspect how the operation handles line boundaries.
println "tea\nrice".indent(2).replace(" ", "·").replace("\n","|")
··tea|··rice|
Two spaces precede every printed item.
Outdent an imported line
A copied checklist or timetable contains meaningful indentation. Adjust the requested leading margin and preserve the subordinate levels so the printed layout still communicates its structure.
println " Lab".indent(-1).replace(" ", "·").replace("\n","|")
·Lab|
Only one leading space is removed.
Indent a packing slip
A stage manager nests two supply items under the main packing heading. Add two spaces to the start of each line before printing it. Brackets around the first line make its indentation visible.
What to watch for
A nonempty result ends with a newline. A negative adjustment removes up to the requested amount of leading whitespace.