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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 01:24:08453browse

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

Padding Strings in Java

When working with strings, it's often necessary to pad them with spaces or other characters to align them or improve readability. Java offers a straightforward way to achieve this using the String.format() method.

Introduced in Java 1.5, String.format() allows you to pad strings to either the left or right by specifying a format string that includes the %- or % symbols, followed by the number of characters to pad and the %s placeholder.

Here's how you can do it:

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);  
}

For instance, let's say you have a string "Howto" and you want to pad it to 20 characters to the right:

System.out.println(padRight("Howto", 20) + "*");

This will output:

Howto               *

Similarly, you can pad strings to the left by using the "%" symbol instead of "-":

System.out.println(padLeft("Howto", 20) + "*");

This will output:

               Howto*

With this method, you can easily manage the alignment and formatting of your strings in your Java applications.

The above is the detailed content of How to Pad Strings in Java Using String.format()?. 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