"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Efficiently Pad Strings in Java?

How Can I Efficiently Pad Strings in Java?

Published on 2024-12-22
Browse:855

How Can I Efficiently Pad Strings in Java?

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*
Latest tutorial More>

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