Padding Strings in Java Made Easy
In Java, the need to pad strings to a certain length often arises. String manipulation can be tedious, but there's a convenient solution using String.format().
String.format() comes to the rescue, providing built-in padding functionality. Using a simple format string, you can control the alignment and width of the resulting string:
For example, the following code demonstrates how to pad strings in Java:
public class StringPadding { public static String padRight(String s, int n) { return String.format("%-" + n + "s", s); } public static String padLeft(String s, int n) { return String.format("%" + n + "s", s); } public static void main(String[] args) { System.out.println(padRight("Howto", 20) + "*"); System.out.println(padLeft("Howto", 20) + "*"); } }
Output:
Howto * Howto*
The above is the detailed content of How Can I Easily Pad Strings to a Specific Length in Java?. For more information, please follow other related articles on the PHP Chinese website!