This tutorial explains how String indent()
works in Java.
String indent()
is used to adjust the indentation of each line of a string based on the passed value. In addition, it also normalizes the line termination. It works by separating the string conceptually using String lines()
, adjusting the indentation, adding \n
(U+000A) at the end of each line as the line terminator, and concatenating the lines into a string.
Using String indent()
Below is the method to be used. It's an instance method and you need to make sure that the string is not null to avoid NullPointerException
.
public String indent(int n)
How the passed value of n
affects the indentation?
- If
n > 0
, it will insert n spaces (U+0020) at the start of each line. - If
n < 0
, it will remove up to n leading white space characters. Any white space character (including\t
) is treated as a single character. - If
n == 0
, it will only change the line terminator.
Below are the examples for each condition.
For example, there's a string with 5, 10, and 4 white space characters at the start of the first, second and third lines respectively. The value of n
is set to 10. Because a positive n
value adds n
white spaces at the start of each line, the output has 15, 10, and 14 white space characters at the start of first, second and third lines respectively. All line terminators are replaced with \n
(U+000A).
String text = " Welcome\n to\r woolha.com";
System.out.println(text.indent(10));
Output:
Welcome
to
woolha.com
In the second example, the value of n
is set to -5. As the value is negative, it removes up to n
white spaces at the beginning of each line. We are going to use the same initial string. Since the first and second lines have at least 5 white spaces, 5 white spaces are removed from the beginning of both lines. The third line only has 4 white spaces characters. As a result, only 4 white space characters are removed from the beginning of the third line. All line terminators are replaced with \n
(U+000A).
String text = " Welcome\n to\r woolha.com";
System.out.println(text.indent(-5));
Output:
Welcome
to
woolha.com
In the last example, the value of n
is set to 0. The numbers of the white space characters on the beginning of each line remain unchanged. The only change is all line terminators are replaced by \n
(U+000A).
String text = " Welcome\n to\r woolha.com";
System.out.println(text.indent(0));
Output:
Welcome
to
woolha.com
That's how String#indent()
works. To use the method, you have to use Java version 12 or above.