Adding whitespace in Java

144,074

Solution 1

I think you are talking about padding strings with spaces.

One way to do this is with string format codes.

For example, if you want to pad a string to a certain length with spaces, use something like this:

String padded = String.format("%-20s", str);

In a formatter, % introduces a format sequence. The - means that the string will be left-justified (spaces will be added at the end of the string). The 20 means the resulting string will be 20 characters long. The s is the character string format code, and ends the format sequence.

Solution 2

Use the StringUtils class, it also includes null check

StringUtils.leftPad(String str, int size)
StringUtils.rightPad(String str, int size)

Solution 3

There's a few approaches for this:

  1. Create a char array then use Arrays.fill, and finally convert to a String
  2. Iterate through a loop adding a space each time
  3. Use String.format

Solution 4

String text = "text";
text += new String(" ");
Share:
144,074

Related videos on Youtube

Sobiaholic
Author by

Sobiaholic

I do code and talks @ IBM.

Updated on July 09, 2022

Comments

  • Sobiaholic
    Sobiaholic almost 2 years

    There is a class trim() to remove white spaces, how about adding/padding?

    Note: " " is not the solution.

    • matbrgz
      matbrgz about 13 years
      Add some examples of "before" and "after".
  • Zoe stands with Ukraine
    Zoe stands with Ukraine about 7 years
    If you had read the entire question, you would have seen: Note: " " is not the solution.
  • surendrapanday
    surendrapanday about 4 years
    The length of the character and space is different, How can I ensure same length?
  • brady
    brady about 4 years
    @surendrapanday I’m sorry but I don’t understand your question. Can you explain more? Maybe an example?
  • surendrapanday
    surendrapanday about 4 years
    This solution produces correct output in the console, but when using the same string in BufferedImage to create Image from the string, this produce output something. aaa : bbb mmm : ccc
  • brady
    brady about 4 years
    @surendrapanday That will depend very much on the Graphics calls you make to render the buffered image. To render an image of formatted text, I would probably explore using Swing components with a layout to do the painting. That's outside the scope of this question and answer, but if you ask a new question, you could link it here.
  • surendrapanday
    surendrapanday about 4 years
    If I use swing component then will there be any behavior change on the different platform (like Andriod, Windows, Mac, etc)