Jump to Real's How-to Main page

Easy String padding

  /**
  ** pad a string S with a size of N with char C 
  ** on the left (True) or on the right(flase)
  **/
  public synchronized String paddingString
      ( String s, int n, char c , boolean paddingLeft  ) {
    StringBuffer str = new StringBuffer(s);
    int strLength  = str.length();
    if ( n > 0 && n > strLength ) {
      for ( int i = 0; i <= n ; i ++ ) {
            if ( paddingLeft ) {
              if ( i < n - strLength ) str.insert( 0, c );
            }
            else {
              if ( i > strLength ) str.append( c );
            }
      }
    }
    return str.toString();
  }
Thanks to Thierry GUIRADO 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-2005
[ home ]