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:
- Create a char array then use Arrays.fill, and finally convert to a String
- Iterate through a loop adding a space each time
- Use String.format
Solution 4
String text = "text";
text += new String(" ");
Related videos on Youtube
Comments
-
Sobiaholic almost 2 years
There is a class
trim()
to remove white spaces, how about adding/padding?Note:
" "
is not the solution.-
matbrgz about 13 yearsAdd some examples of "before" and "after".
-
-
Zoe stands with Ukraine about 7 yearsIf you had read the entire question, you would have seen:
Note: " " is not the solution.
-
surendrapanday about 4 yearsThe length of the character and space is different, How can I ensure same length?
-
brady about 4 years@surendrapanday I’m sorry but I don’t understand your question. Can you explain more? Maybe an example?
-
surendrapanday about 4 yearsThis 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 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 about 4 yearsIf I use swing component then will there be any behavior change on the different platform (like Andriod, Windows, Mac, etc)