View Javadoc

1   package nl.toolforge.core.util.lang;
2   
3   import java.util.ArrayList;
4   import java.util.Iterator;
5   import java.util.List;
6   
7   /***
8    * Extras to <code>org.apache.commons.lang.StringUtils</code>.
9    *
10   * @author D.A. Smedes
11   * @version $Id: NiftyStringUtils.java,v 1.2 2004/11/02 23:57:07 asmedes Exp $
12   */
13  public final class NiftyStringUtils {
14  
15    /***
16     * Splits a <code>String</code> into an <code>Array</code> of <code>String</code>s. Each <code>String</code> is
17     * wrapped maximum at position <code>wrapCount</code>, but taking into account the last position of
18     * <code>wrapChar</code>.
19     *
20     * @param str
21     * @param wrapString
22     * @param wrapCount
23     * @return
24     */
25    public static String[] split(String str, String wrapString, int wrapCount) {
26  
27      if (str == null || wrapString == null || wrapCount <= 1) {
28        return new String[0];
29      }
30  
31      List list = new ArrayList();
32  
33      while (str.length() > wrapCount) {
34  
35        String sub = str.substring(0, wrapCount);
36        int pos = sub.lastIndexOf(wrapString);
37  
38        String substring = null;
39        if (pos > 0) {
40          substring = str.substring(0, pos);
41          list.add(substring);
42  
43          str = str.substring(substring.length() + 1);
44        } else {
45          list.add(sub);
46  
47          str = str.substring(sub.length() + 1);
48        }
49  
50      }
51  
52      // Add the last bit.
53      //
54      list.add(str);
55  
56      String[] ret = new String[list.size()];
57      int i = 0;
58      for (Iterator iter = list.iterator(); iter.hasNext();) {
59        ret[i] = (String) iter.next();
60        i++;
61      }
62      return ret;
63    }
64  
65    /***
66     * Removes blocks of spaces, leaving one intact.
67     *
68     * @param str
69     * @return
70     */
71    public static String deleteWhiteSpaceExceptOne(String str) {
72  
73      String newString = "";
74  
75      char[] c = str.toCharArray();
76  
77      int i = 0;
78      while (i < c.length) {
79  
80        if (Character.isWhitespace(c[i])) {
81          while (Character.isWhitespace(c[i])) {
82            i++;
83          }
84          newString = newString + " ";
85        } else {
86          newString = newString + c[i];
87          i++;
88        }
89      }
90  
91      return newString;
92  
93    }
94  }