Home > Java > javaTutorial > How Can I Efficiently Pad Strings in Java?

How Can I Efficiently Pad Strings in Java?

Mary-Kate Olsen
Release: 2024-12-23 14:06:18
Original
780 people have browsed it

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);
}
Copy after login

Right-Padding:

public static String padRight(String s, int n) {
    return String.format("%-" + n + "s", s);
}
Copy after login

Sample Usage:

public static void main(String args[]) throws Exception {
    System.out.println(padRight("Howto", 20) + "*");
    System.out.println(padLeft("Howto", 20) + "*");
}
Copy after login

Output:

Howto               *
               Howto*
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template