Library contents

Java String.indent

Adjust each line’s indentation and normalize line endings to LF.

A simple example

String.indent

  1. Start with "A" on one line
  2. Do this Indent by two spaces
  3. Result Two spaces, A, newline
Java adds the requested spaces at the front and terminates the line with a newline.

Syntax

Java syntax
public String indent(int n)
JDK 21 method signatures (1)
public String indent(int n)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Indent a packing checklist

A packing slip includes several checklist lines beneath an order heading. Indent each line by the same amount so the checklist reads as a single group when printed.

From the programString items = "Tea\nRice"
Result··Tea|··Rice|
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String items = "Tea\nRice";
        System.out.println(items.indent(2).replace(" ", "·").replace("\n", "|"));
    }
}
Output
··Tea|··Rice|

Dots show the two spaces on each line and bars mark the normalized line endings.

Advertisements

Remove one column from an imported schedule

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.

From the programString schedule = " Lab\n Math"
Result·Lab|Math|
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String schedule = "  Lab\n Math";
        System.out.println(schedule.indent(-1).replace(" ", "·").replace("\n", "|"));
    }
}
Output
·Lab|Math|

Each line loses one leading space. The deeper indentation on Lab remains visible.

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.

GivenCable / Lamp · indent +2
Worked result[ Cable]

What to watch for

A nonempty result ends with a newline. A negative adjustment removes up to the requested amount of leading whitespace.

Documentation for String.indent