Home >Java >javaTutorial >How to Efficiently Pad Strings in Java?

How to Efficiently Pad Strings in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 08:18:13597browse

How to Efficiently Pad Strings in Java?

Java String Padding Techniques

Question:

How can one conveniently pad a string in Java, resembling a StringUtil-like functionality?

Answer:

Java 1.5 introduced a highly effective method for string padding using String.format(). This method enables left or right padding with specified character width.

Implementation:

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

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

Output:

Howto               *
               Howto*

By utilizing the String.format() method, you can effortlessly pad strings to meet your alignment requirements.

The above is the detailed content of How to Efficiently Pad Strings 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