Java 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)
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.javaIndent 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.
class Main {
public static void main(String[] args) throws Exception {
String items = "Tea\nRice";
System.out.println(items.indent(2).replace(" ", "·").replace("\n", "|"));
}
}
··Tea|··Rice|
Dots show the two spaces on each line and bars mark the normalized line endings.
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.
class Main {
public static void main(String[] args) throws Exception {
String schedule = " Lab\n Math";
System.out.println(schedule.indent(-1).replace(" ", "·").replace("\n", "|"));
}
}
·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.
What to watch for
A nonempty result ends with a newline. A negative adjustment removes up to the requested amount of leading whitespace.