Indent And StripIndent Runtime Strings

Shift every line of a runtime-built multi-line string with indent, then recover messy indentation with stripIndent, which strips the smallest common indent.

JavaCli Tooling

Code

snippet
public class LogTable {

    public static void main(String[] args) {
        // indent(n):JDK 12+,每行统一加 n 个空格;
        // 行尾统一成 \n,结尾自动补换行
        String rows = "region=west orders=41\nregion=east orders=57";
        System.out.println(rows.indent(4));

        // indent(-n):反向回收,每行最多去掉 n 个前导空格
        String dedented = rows.indent(4).indent(-2);
        System.out.println(dedented);

        // stripIndent:JDK 13+,按所有行中最小的公共缩进量整体回收
        String messy = "      host=web-1\n        state=up\n  host=db-1";
        System.out.println(messy.stripIndent());
    }
}

How it works

Indent And StripIndent Runtime Strings comes down to the class LogTable and the function main.

Statements that matter

String messy = "      host=web-1\n        state=up\n  host=db-1";
String rows = "region=west orders=41\nregion=east orders=57";
String dedented = rows.indent(4).indent(-2);

Interactive Tools for This Topic

FAQ

How do you run Indent And StripIndent Runtime Strings?
This is a complete program, not a library excerpt — execution starts at the top.