Close

Java - How to Indent multiline String?

[Last Updated: May 21, 2020]

Java String Manipulation Java 

Following example shows how to indent a Java multiline string with n spaces.

By splitting into lines and appending spaces

package com.logicbig.example;

import java.util.Arrays;

public class IndentString {
  public static void main(String[] args) {
      String s = "first\nSecond\nThird";
      s = indentString(s, 5);
      System.out.printf("'%n%s%n'", s);
  }

  private static String indentString(String input, int n) {
      char[] chars = new char[ n];
      Arrays.fill(chars, ' ');
      StringBuilder sb = new StringBuilder();
      boolean first = true;
      for (String line : input.split("\n")) {
          if(!first){
              sb.append("\n");
          }
          sb.append(chars).append(line);
          first=false;
      }

      return sb.toString();
  }
}
'
first
Second
Third
'

By using Java Regex

package com.logicbig.example;

import java.util.Arrays;

public class IndentString2ByRegex {
  public static void main(String[] args) {
      String s = "first\nSecond\nThird";
      s = indentString(s, 5);
      System.out.printf("'%n%s%n'", s);
  }

  private static String indentString(String input, int n) {
      char[] chars = new char[n];
      Arrays.fill(chars, ' ');
      String indented = input.replaceAll("(?m)^", new String(chars));
      return indented;
  }
}
'
first
Second
Third

'

Where in (?m)^:
(1) (?m) enables multiline mode. (see Regex Modifiers)
(2) ^ matches the start of each line.

By using Java 12 String#indent()

Since Java 12 we have java.lang.String#indent() method (Details):

package com.logicbig.example;

public class IndentString3UsingJava12 {
  public static void main(String[] args) {
      String s = "first\nSecond\nThird";
      s = s.indent(5);
      System.out.printf("'%n%s%n'", s);
  }
}
'
first
Second
Third

'

As seen in above last two outputs an additional line break (\n) was appended at the end of the input string.

Example Project

Dependencies and Technologies Used:

  • JDK 12
  • Maven 3.5.4

Indenting multiline String Select All Download
  • java-indent-string-examples
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • IndentString3UsingJava12.java

    See Also