21

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

Note: " " is not the solution.

xyz
  • 21,367
  • 33
  • 107
  • 150
Sobiaholic
  • 2,737
  • 9
  • 32
  • 53

5 Answers5

70

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 on the right 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.

erickson
  • 249,448
  • 50
  • 371
  • 469
  • The length of the character and space is different, How can I ensure same length? – surendrapanday Apr 24 '20 at 12:09
  • @surendrapanday I’m sorry but I don’t understand your question. Can you explain more? Maybe an example? – erickson Apr 24 '20 at 13:11
  • 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 – surendrapanday Apr 24 '20 at 16:31
  • @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. – erickson Apr 24 '20 at 18:29
  • If I use swing component then will there be any behavior change on the different platform (like Andriod, Windows, Mac, etc) – surendrapanday Apr 25 '20 at 01:24
2

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
Community
  • 1
  • 1
stark
  • 819
  • 5
  • 8
1
String text = "text";
text += new String(" ");
Taras Melnyk
  • 2,353
  • 3
  • 27
  • 31
  • 1
    If you had read the entire question, you would have seen: `Note: " " is not the solution.` – Zoe May 26 '17 at 06:58
1

Use the StringUtils class, it also includes null check

StringUtils.leftPad(String str, int size)
StringUtils.rightPad(String str, int size)
Yaniv Levi
  • 346
  • 3
  • 8
0

If you have an Instance of the EditText available at the point in your code where you want add whitespace, then this code below will work. There may be some things to consider, for example the code below may trigger any TextWatcher you have set to this EditText, idk for sure, just saying, but this will work when trying to append blank space like this: " ", hasn't worked.

messageInputBox.dispatchKeyEvent(new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_SPACE, 0, 0, 0, 0,
                        KeyEvent.KEYCODE_ENDCALL));