KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > incava > lang > StringExt


1 package org.incava.lang;
2
3 import java.util.*;
4
5
6 /**
7  * Extensions to the String class.
8  */

9 public class StringExt
10 {
11     /**
12      * Set this to true for debugging output.
13      */

14     public static boolean DEBUG = false;
15
16     /**
17      * Returns an array of strings split at the character delimiter.
18      */

19     public static String JavaDoc[] split(String JavaDoc str, char delim, int max)
20     {
21         return split(str, "" + delim, max);
22     }
23
24     /**
25      * Returns an array of strings split at the string delimiter.
26      */

27     public static String JavaDoc[] split(String JavaDoc str, String JavaDoc delim, int max)
28     {
29         if (max == 1) {
30             return new String JavaDoc[] { str };
31         }
32         else {
33             --max; // adjust count between 0 and 1
34
List splitList = new ArrayList();
35             int nFound = 0;
36             int strlen = str.length();
37             int end = 0;
38             int beg = 0;
39             int delimlen = delim.length();
40             for (int idx = 0; idx < strlen; ++idx) {
41                 if (left(str.substring(idx), delimlen).equals(delim)) {
42                     String JavaDoc substr = str.substring(beg, end);
43                     splitList.add(substr);
44                     beg = end + 1;
45                     if (max > 0 && ++nFound >= max) {
46                         break;
47                     }
48                 }
49                 ++end;
50             }
51
52             if (strlen > beg) {
53                 String JavaDoc tmp = strlen == beg ? "" : str.substring(beg, strlen);
54                 splitList.add(tmp);
55             }
56
57             if (DEBUG) {
58                 System.out.println("split(" + str + ", " + delim + ", " + max + "):");
59                 for (int i = 0; i < splitList.size(); ++i) {
60                     System.out.println(" [" + i + "] = '" + splitList.get(i) + "'");
61                 }
62             }
63             
64             return (String JavaDoc[])splitList.toArray(new String JavaDoc[0]);
65         }
66     }
67
68     /**
69      * Returns an array of strings split at the character delimiter.
70      */

71     public static String JavaDoc[] split(String JavaDoc str, char delim)
72     {
73         return split(str, "" + delim, -1);
74     }
75
76     /**
77      * Returns an array of strings split at the string delimiter.
78      */

79     public static String JavaDoc[] split(String JavaDoc str, String JavaDoc delim)
80     {
81         return split(str, delim, -1);
82     }
83
84     /**
85      * Converts the (possibly quoted) string into a list, delimited by
86      * whitespace and commas..
87      */

88     public static List listify(String JavaDoc str)
89     {
90         // strip leading/trailing single/double quotes
91
if (str.charAt(0) == str.charAt(str.length() - 1) &&
92             (str.charAt(0) == '"' || str.charAt(0) == '\'')) {
93             str = str.substring(1, str.length() - 1);
94         }
95         
96         List list = new ArrayList();
97         StringTokenizer st = new StringTokenizer(str, " \t\n\r\f,");
98         while (st.hasMoreTokens()) {
99             String JavaDoc tk = st.nextToken();
100             list.add(tk);
101         }
102         return list;
103     }
104
105     /**
106      * Returns a string starting with the <code>str</code> parameter, with
107      * <code>ch</code>'s following the string to a length of
108      * <code>length</code>.
109      *
110      * Examples:
111      * pad("abcd", '*', 8) -> "abcd****"
112      * pad("abcd", '*', 3) -> "abcd"
113      */

114     public static String JavaDoc pad(String JavaDoc str, char ch, int length)
115     {
116         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(str);
117         while (buf.length() < length) {
118             buf.append(ch);
119         }
120         return buf.toString();
121     }
122
123     /**
124      * Same as the <code>pad</code> method, but applies the padding to the
125      * left-hand (leading) side of the string.
126      *
127      * Examples:
128      * <pre>
129      * pad("420", '*', 8) -> "*****420"
130      * pad("1144", '*', 3) -> "1144"
131      * </pre>
132      */

133     public static String JavaDoc padLeft(String JavaDoc str, char ch, int length)
134     {
135         return repeat(ch, length - str.length()) + str;
136     }
137
138     public static String JavaDoc pad(String JavaDoc str, int length)
139     {
140         return pad(str, ' ', length);
141     }
142
143     public static String JavaDoc repeat(String JavaDoc str, int length)
144     {
145         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
146         for (int i = 0; i < length; ++i) {
147             buf.append(str);
148         }
149         return buf.toString();
150     }
151
152     public static String JavaDoc repeat(char ch, int length)
153     {
154         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
155         for (int i = 0; i < length; ++i) {
156             buf.append(ch);
157         }
158         return buf.toString();
159     }
160
161     public String JavaDoc toString(double n, int precision)
162     {
163         String JavaDoc str = Double.toString(n);
164         int dot = str.indexOf('.');
165         if (dot != -1 && dot + precision < str.length()) {
166             str = str.substring(0, dot + precision);
167         }
168         return str;
169     }
170
171     /**
172      * Returns the leftmost n characters of the string, not exceeding the length
173      * of the string. Does not throw the annoying IndexOutOfBoundsException.
174      */

175     public static String JavaDoc left(String JavaDoc str, int n)
176     {
177         int x = Math.min(n, str.length());
178         x = Math.max(0, x); // guard against 0
179
return str.substring(0, x);
180     }
181
182     /**
183      * Returns the rightmost n characters of the string, not exceeding the
184      * length of the string. Does not throw the annoying
185      * IndexOutOfBoundsException.
186      */

187     public static String JavaDoc right(String JavaDoc str, int n)
188     {
189         int x = Math.min(n, str.length());
190         x = Math.max(0, x); // guard against 0
191
int s = str.length() - x;
192         return str.substring(s);
193     }
194
195     public static String JavaDoc join(Collection c, String JavaDoc str)
196     {
197         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
198         boolean isFirst = true;
199         Iterator it = c.iterator();
200         while (it.hasNext()) {
201             if (!isFirst) {
202                 buf.append(str);
203             }
204             else {
205                 isFirst = false;
206             }
207             buf.append(it.next());
208         }
209         return buf.toString();
210     }
211
212     public static void test(String JavaDoc str, char del)
213     {
214         System.out.println("----- test: \"" + str + "\" -----");
215         String JavaDoc[] splits = StringExt.split(str, del);
216         System.out.println("#splits: " + splits.length);
217         for (int i = 0; i < splits.length; ++i) {
218             System.out.println(" # " + i + ": " + splits[i]);
219         }
220     }
221
222     public static void test(String JavaDoc str, String JavaDoc del)
223     {
224         System.out.println("----- test: \"" + str + "\" -----");
225         String JavaDoc[] splits = StringExt.split(str, del);
226         System.out.println("#splits: " + splits.length);
227         for (int i = 0; i < splits.length; ++i) {
228             System.out.println(" # " + i + ": " + splits[i]);
229         }
230     }
231
232     public static void main(String JavaDoc[] args)
233     {
234         test("this;is;a;test", ';');
235         test(";is;a;test", ';');
236         test("this;is;a;", ';');
237         test("this;;a;test", ';');
238         test(";this;;a;test;;", ';');
239         test("this is yet another test, it is.", "is");
240     }
241 }
242
243
244
Popular Tags