Padding Strings Seamlessly in Java
Question:
Java lacks an explicit utility for string padding. How can this task be effectively accomplished?
Answer:
Introduced in Java 5, String.format() offers a comprehensive solution for padding strings:
Left-Padding:
public static String padLeft(String s, int n) { return String.format("%" + n + "s", s); }
Right-Padding:
public static String padRight(String s, int n) { return String.format("%-" + n + "s", s); }
Sample Usage:
public static void main(String args[]) throws Exception { 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 Efficiently Pad Strings in Java?. For more information, please follow other related articles on the PHP Chinese website!