Formatting Strings with Padding in Java
Padding strings can be beneficial for aligning text within a specific width or creating visual consistency in output. While there may not be a dedicated "StringUtil" class that includes a padding function, Java provides a powerful alternative using the String.format() method.
Using String.format() for Padding
String.format() allows you to control the formatting of strings using placeholders and various formatting options. For padding, you can use the following syntax:
Implementation
Here's a sample code that demonstrates how to pad strings using String.format():
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[]) throws Exception { System.out.println(padRight("Howto", 20) + "*"); System.out.println(padLeft("Howto", 20) + "*"); }
Output:
Howto * Howto*
This code demonstrates left and right padding of the string "Howto" to a width of 20 characters. The "Howto" text is aligned on the right and left sides within the specified width.
The above is the detailed content of How Can I Pad Strings in Java Using String.format()?. For more information, please follow other related articles on the PHP Chinese website!