Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.indent()

Adds or removes n spaces at the start of every line of text.

Available since: Java 12

Syntax

public String indent(int n)

Parameters

ParameterTypeDescription
nintHow many spaces to add; a negative number removes spaces.

Return value

StringA new string; every line, including the last one, ends with .

Examples

A 4-space indent for a block of code. The method adds a line break at the end itself, so IO.print is used here:

void main() {
    String code = "if (ok) {\n    run();\n}";
    IO.print(code.indent(4));
}

Output:

    if (ok) {
        run();
    }

A negative value removes spaces, and stripIndent() removes the indent common to all lines:

void main() {
    String text = "    one\n      two\n    three";
    IO.print(text.indent(-2));
    IO.println(text.stripIndent());
}

Output:

  one
    two
  three
one
  two
three

Notes

indent() replaces any line breaks with \n and always adds \n at the end. If a line has fewer spaces than asked to remove, all its leading spaces are removed. stripIndent() (Java 15) does to an ordinary string what the compiler does to a text block.

See also

  • String.lines() — Splits a string at line breaks and returns the lines as a stream.
  • Text block """ — A multi-line string literal in triple quotes.
  • String.strip() — Removes any Unicode whitespace from both ends of a string.
  • String.repeat() — Repeats a string the given number of times.

In the tutorial

  • Text blocks and formatting — Multi-line text blocks in Java, formatting strings with formatted, String.format and printf, the %s, %d and %f specifiers and field width.

Thanks for reading!

Donate to the site — we work hard for you.