public class ColumnPrintStringBuffer {
//we cannot extend from Stringbuffer (it's final), so we aggregate it
private StringBuffer sb;
private int columnLength;
private int currentLineLength = 0;
public ColumnPrintStringBuffer(int columnLength) {
sb = new StringBuffer();
this.columnLength = columnLength;
}
public ColumnPrintStringBuffer append(String str) {
StringTokenizer lineTokenizer = new StringTokenizer(str, "\n\r\f");
while (lineTokenizer.hasMoreTokens()) {
appendLine(lineTokenizer.nextToken());
if(lineTokenizer.hasMoreTokens())
sb.append("\n");
}
return this;
}
protected void appendLine(String line){
StringTokenizer wordTokenizer = new StringTokenizer(line, " \t");
if(wordTokenizer.hasMoreTokens()) {
String current = wordTokenizer.nextToken();
String lookAhead = null;
while(wordTokenizer.hasMoreTokens()) {
lookAhead = wordTokenizer.nextToken();
appendWord(current, lookAhead);
current = lookAhead;
lookAhead = null;
}
appendWord(current, lookAhead);
}
}
protected void appendWord(String word, String lookAheadWord) {
if(currentLineLength + word.length() <= columnLength){
currentLineLength += word.length();
sb.append(word);
if(lookAheadWord != null && currentLineLength+ 1 + lookAheadWord.length() <= columnLength) {
currentLineLength++;
sb.append(" ");
} else {
currentLineLength = 0;
if(lookAheadWord != null)
sb.append("\n");
}
} else {
currentLineLength = word.length();
sb.append("\n").append(word);
}
}
@Override
public String toString() {
return sb.toString();
}
public static void main (String[] args) {
String s1 = "The quick brown fox jumped over the lazy dog.\n";
String s2 = "The quick\nbrown fox jumped over\nthe lazy dog.";
ColumnPrintStringBuffer cpsb = new ColumnPrintStringBuffer(10);
cpsb.append(s1);
cpsb.append(s2);
System.out.println(cpsb.toString());
}