Home > Java > javaTutorial > How Can I Pad Strings in Java Using String.format()?

How Can I Pad Strings in Java Using String.format()?

Barbara Streisand
Release: 2024-12-22 04:59:14
Original
701 people have browsed it

How Can I Pad Strings in Java Using String.format()?

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:

  • Left Padding: "%-n s" - This pads the string on the left by n characters.
  • Right Padding: "%n s" - This pads the string on the right by n characters.

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

Output:

Howto               *
               Howto*
Copy after login

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!

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