KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > text > StringFormatter


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.text;
5
6 public class StringFormatter {
7   
8   private final String JavaDoc nl;
9   
10   public StringFormatter() {
11     nl = System.getProperty("line.separator");
12   }
13   
14   public String JavaDoc newline() {
15     return nl;
16   }
17   
18   public String JavaDoc leftPad(int size, Object JavaDoc s) {
19     return pad(false, size, s);
20   }
21   
22
23   public String JavaDoc leftPad(int size, int i) {
24     return leftPad(size, "" + i);
25   }
26   
27   public String JavaDoc rightPad(int size, Object JavaDoc s) {
28     return pad(true, size, s);
29   }
30
31   public String JavaDoc rightPad(int size, int i) {
32     return rightPad(size, "" + i);
33   }
34
35   private String JavaDoc pad(boolean right, int size, Object JavaDoc s) {
36     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
37     buf.append(s);
38     while (buf.length() < size) {
39       if (right) buf.append(" ");
40       else buf.insert(0, " ");
41     }
42     while (buf.length() > size) {
43       buf.deleteCharAt(buf.length() - 1);
44       if (buf.length() == size) {
45         buf.deleteCharAt(buf.length() - 1).append("~");
46       }
47     }
48     return buf.toString();
49   }
50
51 }
Popular Tags