KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > util > StringSplitter


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.util;
11
12 import java.util.ArrayList JavaDoc;
13 import java.util.List JavaDoc;
14
15 /**
16  * Utility class for splitting delimited values.
17  *
18  * @author Pierre van Rooden
19  * @author Kees Jongenburger
20  * @version $Id: StringSplitter.java,v 1.7 2006/06/26 18:15:22 johannes Exp $
21  */

22 public class StringSplitter {
23
24     /**
25      * Simple util method to split delimited values to a list. Useful for attributes.
26      * Similar to <code>String.split()</code>, but returns a List instead of an array, and trims the values.
27      * @param string the string to split
28      * @param delimiter
29      * @return a (modifiable) List containing the elements
30      */

31     static public List JavaDoc split(String JavaDoc string, String JavaDoc delimiter) {
32         List JavaDoc result = new ArrayList JavaDoc();
33         if (string == null) return result;
34         String JavaDoc[] values = string.split(delimiter);
35         for (int i = 0; i < values.length; i++) {
36             result.add(values[i].trim());
37         }
38         return result;
39     }
40
41
42     /**
43      * Simple util method to split comma separated values.
44      * @see #split(String, String)
45      * @param string the string to split
46      * @return a List containing the elements
47      */

48     static public List JavaDoc split(String JavaDoc string) {
49         return split(string, ",");
50     }
51
52     /**
53      * Splits up a String, (using comma delimiter), but takes into account brackets. So
54      * a(b,c,d),e,f(g) will be split up in a(b,c,d) and e and f(g).
55      * @since MMBase-1.8
56      */

57     static public List JavaDoc splitFunctions(CharSequence JavaDoc attribute) {
58         int commaPos = 0;
59         int nested = 0;
60         List JavaDoc result = new ArrayList JavaDoc();
61         int i;
62         int length = attribute.length();
63         for(i = 0; i < length; i++) {
64             char c = attribute.charAt(i);
65             if ((c == ',') || (c == ';')){
66                 if(nested == 0) {
67                     result.add(attribute.subSequence(commaPos, i).toString().trim());
68                     commaPos = i + 1;
69                 }
70             } else if (c == '(') {
71                 nested++;
72             } else if (c == ')') {
73                 nested--;
74             }
75         }
76         if (i > 0) {
77             result.add(attribute.toString().substring(commaPos).trim());
78         }
79         return result;
80     }
81     
82
83 }
84
Popular Tags