Skip to main content

APIzation: Replication Package

[Q#7506771][A#7506812] How to adjust trailing whitespace?

https://stackoverflow.com/q/7506771

I am writing to a file in java but the strings that are input into the file are different, how do i adjust the trailing whitespace depending on the length of the string. for example

Answer

https://stackoverflow.com/a/7506812

You can use String.format(): will give you:

APIzation

System.out.println(String.format("[%-20s]", "foo"));
[foo                 ]
package com.stackoverflow.api;

public class Human7506812 {

  public static String padStringRight(int lengthAfterPadding) {
    return String.format("[%-" + lengthAfterPadding + "s]", "foo");
  }
}

package com.stackoverflow.api;

/**
 * How to adjust trailing whitespace?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/7506812">https://stackoverflow.com/a/7506812</a>
 */
public class APIzator7506812 {

  public static String adjustWhitespace() throws Exception {
    return String.format("[%-20s]", "foo");
  }
}