Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pad a String in Java?

Is there some easy way to pad Strings in Java?

Seems like something that should be in some StringUtil-like API, but I can't find anything that does this.

like image 854
pvgoddijn Avatar asked Dec 23 '08 09:12

pvgoddijn


People also ask

How do you add padding to a string?

The standard way to add padding to a string in Python is using the str. rjust() function. It takes the width and padding to be used. If no padding is specified, the default padding of ASCII space is used.

What is padding a string?

String padding refers to adding, usually, non-informative characters to a string to one or both ends of it. This is most often done for output formatting and alignment purposes, but it can have useful practical applications.

How can I pad a string with zeros on the left?

leftPad() method to left pad a string with zeros, by adding leading zeros to string.

How do I add 0 to a string?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding.


1 Answers

Since Java 1.5, String.format() can be used to left/right pad a given string.

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

And the output is:

Howto               *                Howto* 
like image 180
RealHowTo Avatar answered Sep 20 '22 01:09

RealHowTo