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 static String padRight(String s, int n) {
     return String.format("%1$-" + n + "s", s);  
}

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(padRight("Howto", 20) + "*");
 System.out.println(padLeft("Howto", 25) + "*");
}
/*
  output :
     Howto               *
                         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.



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-2012
[ home ]