Share this page 

Justify a string with wordwrapTag(s): String/Number


public class StringUtils {

  private StringUtils() {}

  /*
    justify a string,
    here only left justification is implemented
  */
  public static String justifyLeft( int width,String st) {
    StringBuffer buf = new StringBuffer(st);
    int lastspace = -1;
    int linestart = 0;
    int i = 0;

    while (i < buf.length()) {
       if ( buf.charAt(i) == ' ' ) lastspace = i;
       if ( buf.charAt(i) == '\n' ) {
          lastspace = -1;
          linestart = i+1;
       }
       if (i > linestart + width - 1 ) {
          if (lastspace != -1) {
             buf.setCharAt(lastspace,'\n');
             linestart = lastspace+1;
             lastspace = -1;
          }
          else {
             buf.insert(i,'\n');
             linestart = i+1;
          }
       }
       i++;
    }
    return buf.toString();
 }

 public static void main(String arg[]){
    String formatted_string;
    String original_string=
       "01234567890123456789   01234567890 0123   4565789 ";

    formatted_string = StringUtils.justifyLeft(25,original_string);

    System.out.println("---------");
    System.out.println(original_string);
    System.out.println("---------");
    System.out.println(formatted_string);
    /*
      output :
      ---------
      01234567890123456789   01234567890 0123   4565789
      ---------
      01234567890123456789
      01234567890 0123
      4565789
    */
  }
}