Justify a string with wordwrap

From CodeCodex

Revision as of 05:05, 7 January 2012 by Nostromo (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Implementations[edit]

Java[edit]

 /*
    justify a string, 
    here only left justification is implemented
*/
public class FormatLine {
  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 = FormatLine.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
    */
  }
}