Home >Java >javaTutorial >How Can I Easily Pad Strings to a Specific Length in Java?

How Can I Easily Pad Strings to a Specific Length in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-28 21:38:101006browse

How Can I Easily Pad Strings to a Specific Length in Java?

Padding Strings in Java Made Easy

In Java, the need to pad strings to a certain length often arises. String manipulation can be tedious, but there's a convenient solution using String.format().

String.format() comes to the rescue, providing built-in padding functionality. Using a simple format string, you can control the alignment and width of the resulting string:

  • Left Padding: Add %-s to left-pad with spaces to the specified width.
  • Right Padding: Add %-number>s to right-pad with spaces to the specified width.

For example, the following code demonstrates how to pad strings in Java:

public class StringPadding {

    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) {
        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 Easily Pad Strings to a Specific Length in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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