1 4 package com.tc.text; 5 6 import java.util.Arrays ; 7 import java.util.Iterator ; 8 import java.util.List ; 9 10 public class ConsoleParagraphFormatter implements ParagraphFormatter { 11 12 private final StringFormatter sf; 13 private final int maxWidth; 14 15 public ConsoleParagraphFormatter(int maxWidth, StringFormatter stringFormatter) { 16 this.maxWidth = maxWidth; 17 this.sf = stringFormatter; 18 } 19 20 public String format(String in) { 21 StringBuffer buf = new StringBuffer (); 22 if (in == null) throw new AssertionError (); 23 List words = parseWords(in); 24 int lineWidth = 0; 25 for (Iterator i = words.iterator(); i.hasNext();) { 26 String currentWord = (String ) i.next(); 27 if (lineWidth + currentWord.length() > maxWidth) { 28 if (lineWidth > 0) { 29 buf.append(sf.newline()); 30 } 31 lineWidth = currentWord.length(); 32 } else { 33 if (lineWidth > 0) { 34 buf.append(" "); 35 } 36 lineWidth += currentWord.length(); 37 } 38 buf.append(currentWord); 39 } 40 return buf.toString(); 41 } 42 43 private List parseWords(String in) { 44 String [] words = in.split("\\s+"); 45 return Arrays.asList(words); 46 } 47 48 } 49 | Popular Tags |