| midrange.com code scratchpad | 
				
					| 
							
								| Name:WordWrap | Scriptlanguage:Java | Tabwidth:4 | Date:09/19/2008 11:52:40 am | IP:Logged |  | 
				
					| Description:Shows how to use regular expressions to split lines at the specified character count without splitting words.  Also splits on "new line". | 
				
					| Code: 
							
								
								
								| 
    import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 public class WordWrap {
     private Pattern wrapRE = null;
     public WordWrap(int lineLength) {
        this.wrapRE = Pattern.compile("(\\S\\S{" + lineLength + ",}|.{1," + lineLength + "})(\\s+|$)");
        System.out.println("Compiled pattern:" + wrapRE.pattern());
    }
     public String[] wrapText(String str) {
        List list = new LinkedList();
        Matcher m = this.wrapRE.matcher(str);
        while (m.find()) {
            list.add(m.group());
        }
        return (String[]) list.toArray(new String[list.size()]);
    }
     public static void main(String args[]) {
        WordWrap ww = new WordWrap(40);        
        
        String str = "This is a line of text 111111. T2his i2s al2so a2 lin2e" +
        "will eventuallyrunoverats  string is longer than normal. Somwer" +
        "some more text\nover at some point simple stri."+
        "This is the last sentence in the paragraph."; 
        
        String[] results = ww.wrapText(str);
         for (int i = 0; i < results.length; i++) {
            System.out.println(results[i]);
        }
    }
}
  |  | 
				
					|  |