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:
  1. import java.util.LinkedList;
  2. import java.util.List;
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5.  
  6. public class WordWrap {
  7.  
  8.     private Pattern wrapRE = null;
  9.  
  10.     public WordWrap(int lineLength) {
  11.         this.wrapRE = Pattern.compile("(\\S\\S{" + lineLength + ",}|.{1," + lineLength + "})(\\s+|$)");
  12.         System.out.println("Compiled pattern:" + wrapRE.pattern());
  13.     }
  14.  
  15.     public String[] wrapText(String str) {
  16.         List list = new LinkedList();
  17.         Matcher m = this.wrapRE.matcher(str);
  18.         while (m.find()) {
  19.             list.add(m.group());
  20.         }
  21.         return (String[]) list.toArray(new String[list.size()]);
  22.     }
  23.  
  24.     public static void main(String args[]) {
  25.         WordWrap ww = new WordWrap(40);        
  26.         
  27.         String str = "This is a line of text 111111. T2his i2s al2so a2 lin2e" +
  28.         "will eventuallyrunoverats  string is longer than normal. Somwer" +
  29.         "some more text\nover at some point simple stri."+
  30.         "This is the last sentence in the paragraph."; 
  31.         
  32.         String[] results = ww.wrapText(str);
  33.  
  34.         for (int i = 0; i < results.length; i++) {
  35.             System.out.println(results[i]);
  36.         }
  37.     }
  38. }
  39.  
© 2004-2019 by midrange.com generated in 0.009s valid xhtml & css