KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openlaszlo > utils > StringUtils


1 /* *****************************************************************************
2  * StringUtils.java
3  * ****************************************************************************/

4
5 /* J_LZ_COPYRIGHT_BEGIN *******************************************************
6 * Copyright 2001-2004 Laszlo Systems, Inc. All Rights Reserved. *
7 * Use is subject to license terms. *
8 * J_LZ_COPYRIGHT_END *********************************************************/

9
10 package org.openlaszlo.utils;
11 import java.util.*;
12
13 /**
14  * A utility class containing string utility functions.
15  *
16  * @author Oliver Steele
17  */

18 public abstract class StringUtils {
19     /**
20      * Splits a string containing <var>n</var> occurrences of
21      * <var>delim</var> into <var>n+1</var> strings that don't contain
22      * <var>delim</var> (and whose occurrences in <var>str</var> are
23      * bounded by <var>delim</var>).
24      *
25      * <p>For example, <code>split("a,b,,c", ",")<code> evaluates to
26      * <code>{"a", "b", "", "c"}</code>.
27
28      * <p><code>split("/", "/") -> ["", ""]</code>
29      *
30      * @param str a <code>String</code> value
31      * @param delim a <code>char</code> value
32      * @return a <code>String[]</code> value
33      */

34     public static String JavaDoc[] split(String JavaDoc str, String JavaDoc delim)
35     {
36         List lines = new Vector();
37         int startPos = 0;
38         while (true) {
39             int endPos = indexOf(str, delim, startPos);
40             if (endPos == -1) {
41                 if (startPos > 0 || startPos < str.length()) {
42                     lines.add(str.substring(startPos));
43                 }
44                 break;
45             }
46             lines.add(str.substring(startPos, endPos));
47             startPos = endPos + delim.length();
48         }
49         {
50             String JavaDoc[] result = new String JavaDoc[lines.size()];
51             int i = 0;
52             for (Iterator e = lines.iterator(); e.hasNext(); ) {
53                 result[i] = (String JavaDoc) e.next();
54                 i++;
55             }
56             return result;
57         }
58     }
59     
60     /**
61      * Returns a single string that interpolates the strings in
62      * <var>lines</var> by the delimiters <var>delim</var>.
63      *
64      * For example, <code>join({"a","b","c"}, ",")</code> would
65      * evaluate to <code>"a,b,c"</code> (if Java had a literal
66      * expression notation for arrays).
67      *
68      * @param lines a <code>String[]</code> value
69      * @param delim a <code>char</code> value
70      * @return a <code>String</code> value
71      */

72     public static String JavaDoc join(String JavaDoc[] lines, String JavaDoc delim) {
73         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
74         for (int i = 0; i < lines.length; i++) {
75             if (i > 0) {
76                 buffer.append(delim);
77             }
78             buffer.append(lines[i]);
79         }
80         return buffer.toString();
81     }
82
83     /** List<Object>, String -> String */
84     public static String JavaDoc join(List words, String JavaDoc delim) {
85         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
86         for (Iterator iter = words.iterator(); iter.hasNext(); ) {
87             buffer.append(iter.next());
88             if (iter.hasNext()) {
89                 buffer.append(delim);
90             }
91         }
92         return buffer.toString();
93     }
94
95     /** Return the index of the first occurrence of value in str that
96      * is later than or equal to offset.
97      * @param str a String
98      * @param value a String
99      * @param offset a String
100      * @return an int
101      */

102     public static int indexOf(String JavaDoc str, String JavaDoc value, int offset) {
103         if (value.length() == 0) {
104             throw new IllegalArgumentException JavaDoc();
105         }
106         while (offset < str.length()) {
107             int pos = str.indexOf(value.charAt(0), offset);
108             if (pos == -1) {
109                 return pos;
110             }
111             for (int i = 1; ; i++) {
112                 if (i >= value.length()) {
113                     return pos;
114                 }
115                 if (pos + i >= str.length() ||
116                     str.charAt(pos + i) != value.charAt(i)) {
117                     break;
118                 }
119             }
120             offset = pos + 1;
121         }
122         return -1;
123     }
124
125     /** Turn CRs into LFs.
126      *
127      * Note: not implemented for DOS (CRLF) line feeds. Will turn
128      * them into double lines, which will mess up multi-line string
129      * literals.
130      *
131      * @param src a string
132      * @return a string
133      */

134     public static String JavaDoc normalizeLineEndings(String JavaDoc src) {
135         if (src.indexOf('\r') >= 0) {
136             return StringUtils.join(StringUtils.split(src, "\r"), "\n");
137         }
138         return src;
139     }
140
141     /**
142      * Parse an int, interpreting a leading 0x or # to mean
143      * the text is in hexidecimal
144      *
145      * @param src a string
146      */

147     public static int parseInt(String JavaDoc src) {
148         if (src.length() > 1 && src.charAt(0) == '#') {
149             return Integer.parseInt(src.substring(1), 16);
150         }
151         else if (src.length() > 2 && src.charAt(0) == '0'
152                 && src.charAt(1) == 'x') {
153             return Integer.parseInt(src.substring(2), 16);
154         } else {
155             return Integer.parseInt(src);
156         }
157     }
158
159
160     /**
161      * Replaces old character with new string.
162      *
163      * @param str string to replace old character with new string
164      * @param oldChar old character to replace in string
165      * @param newStr new string to replace old character with
166      * @return string with replaced string
167      */

168     public static String JavaDoc replace(String JavaDoc str, char oldChar, String JavaDoc newStr)
169     {
170         // offset: length(newString) - length(oldChar)
171
int os = newStr.length()-1;
172         int bufOS = 0;
173         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(str);
174         int i = str.indexOf(oldChar);
175         while (i != -1) {
176             // Index of buffer needs to be adjusted by the number of times new
177
// string is replaced
178
buf.replace(i+bufOS, i+bufOS+1, newStr);
179             bufOS += os;
180             i = str.indexOf(oldChar, i+1);
181         }
182         return buf.toString();
183     }
184
185     /**
186      * Replace index in string with given character
187      * @param str string to start with
188      * @param index to use
189      * @param char to replace with
190      * @return str with char replaced
191      */

192     public static String JavaDoc setCharAt(String JavaDoc str, int x, char c)
193         throws IndexOutOfBoundsException JavaDoc {
194         
195         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(str);
196         buf.setCharAt(x, c);
197         return buf.toString();
198
199     }
200
201     /**
202      * Replaces old string with new string.
203      *
204      * @param str string to replace old character with new string
205      * @param oldStr old string to replace in string
206      * @param newStr new string to replace old character with
207      * @return string with replaced string
208      */

209     public static String JavaDoc replace(String JavaDoc str, String JavaDoc oldStr, String JavaDoc newStr)
210     {
211         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
212         int curIndex = 0;
213         int len = oldStr.length();
214
215         while(true) {
216             int x = str.indexOf(oldStr, curIndex);
217             if (x != -1) {
218                 buf.append(str.substring(curIndex, x));
219                 buf.append(newStr);
220                 curIndex = x + len;
221             } else {
222                 buf.append(str.substring(curIndex));
223                 break;
224             }
225         }
226         
227         return buf.toString();
228     }
229
230
231     /**
232      * Expand property values in a string. Property values need to be enclosed
233      * in ${}. For example, the string
234      * "${file.separator}lps${file.separator}logs" will be converted to
235      * "/lps/logs".
236      * @param str string to expand property values
237      * @return expanded string or null, if a property variable wasn't closed
238      * properly or a specified property value doesn't exist.
239      */

240     public static String JavaDoc expandPropertyValues(String JavaDoc str)
241         throws Exception JavaDoc
242     {
243         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
244
245         int i0, i1;
246         int pos = 0;
247         String JavaDoc propName;
248         String JavaDoc propValue;
249         while (pos < str.length()) {
250             i0 = str.indexOf("${", pos);
251             if (i0 == -1) {
252                 buf.append(str.substring(pos));
253                 break;
254             }
255             i1 = str.indexOf('}', i0);
256             if (i1 == -1)
257                 throw new Exception JavaDoc("missing close bracket: '}'");
258
259             // Append part of string we've skipped
260
if (i0 > pos)
261                 buf.append(str.substring(pos, i0));
262
263             propName = str.substring(i0+2, i1);
264             try {
265                 propValue = System.getProperty(propName);
266                 if (propValue == null)
267                     throw new Exception JavaDoc("System property " + propName +
268                                          " does not exist");
269             } catch (SecurityException JavaDoc e) {
270                 // TODO [2004-07-14 bloch]: log exception?
271
propValue = "";
272             }
273
274             buf.append(propValue);
275
276             pos = i1+1;
277         }
278         return buf.toString();
279     }
280 }
281
Popular Tags