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*
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3