Real'sHowTo AddThis Feed Button
Custom Search

Easy String paddingTag(s): String/Number


[JDK 1.5]
Since 1.5, String.format() can be used to left/right pad a given string.
public class StringUtils {
  private StringUtils() {}

  // pad with " " to the right to the given length (n)
  public static String padRight(String s, int n) {
    return String.format("%1$-" + n + "s", s);
  }

  // pad with " " to the left to the given length (n)
  public static String padLeft(String s, int n) {
    return String.format("%1$" + n + "s", s);
  }

  public static void main(String args[]) throws Exception {
    System.out.println(StringUtils.padRight("Howto", 20) + "*");
    System.out.println(StringUtils.padLeft("Howto", 20) + "*");
  }

  /* output

Howto               *
               Howto*

  */
}
These one-liners are useful to pad to a fix length with a given character.
public class Test {

  public static void main(String args[]) throws Exception {
    System.out.println(String.format("%10s", "howto").replace(' ', '*'));
    System.out.println(String.format("%-10s", "howto").replace(' ', '*'));
  }

/*  output

*****howto
howto*****

*/

}
To mask a password in a log file :
public class Test {
  public static void main(String args[]) throws Exception {
    String password = "howto";
    System.out.println(password);
    System.out.println(String.format("%"+password.length()+"s", "").replace(' ', '*'));
  }

  /* output

howto
*****

  */

}

[JDK1.4 or less]
/**
* Pads a String <code>s</code> to take up <code>n</code>
* characters, padding with char <code>c</code> on the
* left (<code>true</code>) or on the right (<code>false</code>).
* Returns <code>null</code> if passed a <code>null</code>
* String.
**/
public static String paddingString(String s, int n, char c, boolean paddingLeft) {
  if (s == null) {
    return s;
  }
  int add = n - s.length(); // may overflow int size... should not be a problem in real life
  if(add <= 0){
    return s;
  }
  StringBuffer str = new StringBuffer(s);
  char[] ch = new char[add];
  Arrays.fill(ch, c);
  if(paddingLeft){
    str.insert(0, ch);
  }
  else {
    str.append(ch);
  }
  return str.toString();
}

Thanks to P. Buluschek for this snippet.

blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]