Methods for outputting aligned strings in Java include: using format specifiers to specify alignment, padding characters, and field width. Use the String.format() method. Use the StringUtils.center() method of the Apache Commons Lang library.
String alignment in Java
How to output aligned strings?
Java provides a variety of methods to output aligned strings, including:
Using format specifiers
Format specifiers Can be used to specify the alignment of a string. The format specifier consists of the following parts:
For example, the following code right-aligns the string "Hello" and fills the gaps:
<code class="java">System.out.printf("%10s", "Hello");</code>
Use the String.format() method
String.format()
The method can also be used to align strings. It uses a similar syntax to the format specifier:
<code class="java">String formattedString = String.format("%10s", "Hello");</code>
Using the StringUtils library (Apache Commons Lang)
The Apache Commons Lang library provides a StringUtils
Class containing many utility methods for string manipulation, including alignment methods.
For example, the following code center-aligns the string "Hello":
<code class="java">String centeredString = StringUtils.center("Hello", 10);</code>
The above is the detailed content of How to align java output strings. For more information, please follow other related articles on the PHP Chinese website!