midrange.com code scratchpad
Name:
WordWrap-Single word
Scriptlanguage:
Java
Tabwidth:
4
Date:
09/19/2008 02:04:16 pm
IP:
Logged
Description:
The user was to lazy to give a description
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 str = "Thisisalineoftext111111.T2hisi2sal2soa2lin2e" +
  33.         "willeventuallyrunoveratsstringislongerthannormal.Somwer" +
  34.         "somemoretext\noveratsomepointsimplestri."+
  35.         "Thisisthelastsentenceintheparagraph.";         
  36.         
  37.         String[] results = ww.wrapText(str);
  38.  
  39.         for (int i = 0; i < results.length; i++) {
  40.             System.out.println(results[i]);
  41.         }
  42.     }
  43. }
  44.  
© 2004-2019 by midrange.com generated in 0.01s valid xhtml & css