KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > lang > StringUtils


1 /*
2  * Copyright 2002-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.commons.lang;
17
18 import java.util.ArrayList JavaDoc;
19 import java.util.Iterator JavaDoc;
20 import java.util.List JavaDoc;
21
22 /**
23  * <p>Operations on {@link java.lang.String} that are
24  * <code>null</code> safe.</p>
25  *
26  * <ul>
27  * <li><b>IsEmpty/IsBlank</b>
28  * - checks if a String contains text</li>
29  * <li><b>Trim/Strip</b>
30  * - removes leading and trailing whitespace</li>
31  * <li><b>Equals</b>
32  * - compares two strings null-safe</li>
33  * <li><b>IndexOf/LastIndexOf/Contains</b>
34  * - null-safe index-of checks
35  * <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b>
36  * - index-of any of a set of Strings</li>
37  * <li><b>ContainsOnly/ContainsNone</b>
38  * - does String contains only/none of these characters</li>
39  * <li><b>Substring/Left/Right/Mid</b>
40  * - null-safe substring extractions</li>
41  * <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b>
42  * - substring extraction relative to other strings</li>
43  * <li><b>Split/Join</b>
44  * - splits a String into an array of substrings and vice versa</li>
45  * <li><b>Remove/Delete</b>
46  * - removes part of a String</li>
47  * <li><b>Replace/Overlay</b>
48  * - Searches a String and replaces one String with another</li>
49  * <li><b>Chomp/Chop</b>
50  * - removes the last part of a String</li>
51  * <li><b>LeftPad/RightPad/Center/Repeat</b>
52  * - pads a String</li>
53  * <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b>
54  * - changes the case of a String</li>
55  * <li><b>CountMatches</b>
56  * - counts the number of occurrences of one String in another</li>
57  * <li><b>IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable</b>
58  * - checks the characters in a String</li>
59  * <li><b>DefaultString</b>
60  * - protects against a null input String</li>
61  * <li><b>Reverse/ReverseDelimited</b>
62  * - reverses a String</li>
63  * <li><b>Abbreviate</b>
64  * - abbreviates a string using ellipsis</li>
65  * <li><b>Difference</b>
66  * - compares two Strings and reports on their differences</li>
67  * <li><b>LevensteinDistance</b>
68  * - the number of changes needed to change one String into another</li>
69  * </ul>
70  *
71  * <p>The <code>StringUtils</code> class defines certain words related to
72  * String handling.</p>
73  *
74  * <ul>
75  * <li>null - <code>null</code></li>
76  * <li>empty - a zero-length string (<code>""</code>)</li>
77  * <li>space - the space character (<code>' '</code>, char 32)</li>
78  * <li>whitespace - the characters defined by {@link Character#isWhitespace(char)}</li>
79  * <li>trim - the characters &lt;= 32 as in {@link String#trim()}</li>
80  * </ul>
81  *
82  * <p><code>StringUtils</code> handles <code>null</code> input Strings quietly.
83  * That is to say that a <code>null</code> input will return <code>null</code>.
84  * Where a <code>boolean</code> or <code>int</code> is being returned
85  * details vary by method.</p>
86  *
87  * <p>A side effect of the <code>null</code> handling is that a
88  * <code>NullPointerException</code> should be considered a bug in
89  * <code>StringUtils</code> (except for deprecated methods).</p>
90  *
91  * <p>Methods in this class give sample code to explain their operation.
92  * The symbol <code>*</code> is used to indicate any input including <code>null</code>.</p>
93  *
94  * @see java.lang.String
95  * @author <a HREF="http://jakarta.apache.org/turbine/">Apache Jakarta Turbine</a>
96  * @author GenerationJavaCore
97  * @author <a HREF="mailto:jon@latchkey.com">Jon S. Stevens</a>
98  * @author <a HREF="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
99  * @author <a HREF="mailto:gcoladonato@yahoo.com">Greg Coladonato</a>
100  * @author <a HREF="mailto:bayard@generationjava.com">Henri Yandell</a>
101  * @author <a HREF="mailto:ed@apache.org">Ed Korthof</a>
102  * @author <a HREF="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
103  * @author Stephen Colebourne
104  * @author <a HREF="mailto:fredrik@westermarck.com">Fredrik Westermarck</a>
105  * @author Holger Krauth
106  * @author <a HREF="mailto:alex@purpletech.com">Alexander Day Chaffee</a>
107  * @author <a HREF="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>
108  * @author Arun Mammen Thomas
109  * @author Gary Gregory
110  * @author Phil Steitz
111  * @author Al Chou
112  * @author Michael Davey
113  * @since 1.0
114  * @version $Id: StringUtils.java 161243 2005-04-14 04:30:28Z ggregory $
115  */

116 public class StringUtils {
117     // Performance testing notes (JDK 1.4, Jul03, scolebourne)
118
// Whitespace:
119
// Character.isWhitespace() is faster than WHITESPACE.indexOf()
120
// where WHITESPACE is a string of all whitespace characters
121
//
122
// Character access:
123
// String.charAt(n) versus toCharArray(), then array[n]
124
// String.charAt(n) is about 15% worse for a 10K string
125
// They are about equal for a length 50 string
126
// String.charAt(n) is about 4 times better for a length 3 string
127
// String.charAt(n) is best bet overall
128
//
129
// Append:
130
// String.concat about twice as fast as StringBuffer.append
131
// (not sure who tested this)
132

133     /**
134      * The empty String <code>""</code>.
135      * @since 2.0
136      */

137     public static final String JavaDoc EMPTY = "";
138
139     /**
140      * Represents a failed index search.
141      * @since 2.1
142      */

143     public static final int INDEX_NOT_FOUND = -1;
144
145     /**
146      * <p>The maximum size to which the padding constant(s) can expand.</p>
147      */

148     private static final int PAD_LIMIT = 8192;
149
150     /**
151      * <p>An array of <code>String</code>s used for padding.</p>
152      *
153      * <p>Used for efficient space padding. The length of each String expands as needed.</p>
154      */

155     private static final String JavaDoc[] PADDING = new String JavaDoc[Character.MAX_VALUE];
156
157     static {
158         // space padding is most common, start with 64 chars
159
PADDING[32] = " ";
160     }
161
162     /**
163      * <p><code>StringUtils</code> instances should NOT be constructed in
164      * standard programming. Instead, the class should be used as
165      * <code>StringUtils.trim(" foo ");</code>.</p>
166      *
167      * <p>This constructor is public to permit tools that require a JavaBean
168      * instance to operate.</p>
169      */

170     public StringUtils() {
171         // no init.
172
}
173
174     // Empty checks
175
//-----------------------------------------------------------------------
176
/**
177      * <p>Checks if a String is empty ("") or null.</p>
178      *
179      * <pre>
180      * StringUtils.isEmpty(null) = true
181      * StringUtils.isEmpty("") = true
182      * StringUtils.isEmpty(" ") = false
183      * StringUtils.isEmpty("bob") = false
184      * StringUtils.isEmpty(" bob ") = false
185      * </pre>
186      *
187      * <p>NOTE: This method changed in Lang version 2.0.
188      * It no longer trims the String.
189      * That functionality is available in isBlank().</p>
190      *
191      * @param str the String to check, may be null
192      * @return <code>true</code> if the String is empty or null
193      */

194     public static boolean isEmpty(String JavaDoc str) {
195         return str == null || str.length() == 0;
196     }
197
198     /**
199      * <p>Checks if a String is not empty ("") and not null.</p>
200      *
201      * <pre>
202      * StringUtils.isNotEmpty(null) = false
203      * StringUtils.isNotEmpty("") = false
204      * StringUtils.isNotEmpty(" ") = true
205      * StringUtils.isNotEmpty("bob") = true
206      * StringUtils.isNotEmpty(" bob ") = true
207      * </pre>
208      *
209      * @param str the String to check, may be null
210      * @return <code>true</code> if the String is not empty and not null
211      */

212     public static boolean isNotEmpty(String JavaDoc str) {
213         return str != null && str.length() > 0;
214     }
215
216     /**
217      * <p>Checks if a String is whitespace, empty ("") or null.</p>
218      *
219      * <pre>
220      * StringUtils.isBlank(null) = true
221      * StringUtils.isBlank("") = true
222      * StringUtils.isBlank(" ") = true
223      * StringUtils.isBlank("bob") = false
224      * StringUtils.isBlank(" bob ") = false
225      * </pre>
226      *
227      * @param str the String to check, may be null
228      * @return <code>true</code> if the String is null, empty or whitespace
229      * @since 2.0
230      */

231     public static boolean isBlank(String JavaDoc str) {
232         int strLen;
233         if (str == null || (strLen = str.length()) == 0) {
234             return true;
235         }
236         for (int i = 0; i < strLen; i++) {
237             if ((Character.isWhitespace(str.charAt(i)) == false)) {
238                 return false;
239             }
240         }
241         return true;
242     }
243
244     /**
245      * <p>Checks if a String is not empty (""), not null and not whitespace only.</p>
246      *
247      * <pre>
248      * StringUtils.isNotBlank(null) = false
249      * StringUtils.isNotBlank("") = false
250      * StringUtils.isNotBlank(" ") = false
251      * StringUtils.isNotBlank("bob") = true
252      * StringUtils.isNotBlank(" bob ") = true
253      * </pre>
254      *
255      * @param str the String to check, may be null
256      * @return <code>true</code> if the String is
257      * not empty and not null and not whitespace
258      * @since 2.0
259      */

260     public static boolean isNotBlank(String JavaDoc str) {
261         int strLen;
262         if (str == null || (strLen = str.length()) == 0) {
263             return false;
264         }
265         for (int i = 0; i < strLen; i++) {
266             if ((Character.isWhitespace(str.charAt(i)) == false)) {
267                 return true;
268             }
269         }
270         return false;
271     }
272
273     // Trim
274
//-----------------------------------------------------------------------
275
/**
276      * <p>Removes control characters (char &lt;= 32) from both
277      * ends of this String, handling <code>null</code> by returning
278      * an empty String ("").</p>
279      *
280      * <pre>
281      * StringUtils.clean(null) = ""
282      * StringUtils.clean("") = ""
283      * StringUtils.clean("abc") = "abc"
284      * StringUtils.clean(" abc ") = "abc"
285      * StringUtils.clean(" ") = ""
286      * </pre>
287      *
288      * @see java.lang.String#trim()
289      * @param str the String to clean, may be null
290      * @return the trimmed text, never <code>null</code>
291      * @deprecated Use the clearer named {@link #trimToEmpty(String)}.
292      * Method will be removed in Commons Lang 3.0.
293      */

294     public static String JavaDoc clean(String JavaDoc str) {
295         return str == null ? EMPTY : str.trim();
296     }
297
298     /**
299      * <p>Removes control characters (char &lt;= 32) from both
300      * ends of this String, handling <code>null</code> by returning
301      * <code>null</code>.</p>
302      *
303      * <p>The String is trimmed using {@link String#trim()}.
304      * Trim removes start and end characters &lt;= 32.
305      * To strip whitespace use {@link #strip(String)}.</p>
306      *
307      * <p>To trim your choice of characters, use the
308      * {@link #strip(String, String)} methods.</p>
309      *
310      * <pre>
311      * StringUtils.trim(null) = null
312      * StringUtils.trim("") = ""
313      * StringUtils.trim(" ") = ""
314      * StringUtils.trim("abc") = "abc"
315      * StringUtils.trim(" abc ") = "abc"
316      * </pre>
317      *
318      * @param str the String to be trimmed, may be null
319      * @return the trimmed string, <code>null</code> if null String input
320      */

321     public static String JavaDoc trim(String JavaDoc str) {
322         return str == null ? null : str.trim();
323     }
324
325     /**
326      * <p>Removes control characters (char &lt;= 32) from both
327      * ends of this String returning <code>null</code> if the String is
328      * empty ("") after the trim or if it is <code>null</code>.
329      *
330      * <p>The String is trimmed using {@link String#trim()}.
331      * Trim removes start and end characters &lt;= 32.
332      * To strip whitespace use {@link #stripToNull(String)}.</p>
333      *
334      * <pre>
335      * StringUtils.trimToNull(null) = null
336      * StringUtils.trimToNull("") = null
337      * StringUtils.trimToNull(" ") = null
338      * StringUtils.trimToNull("abc") = "abc"
339      * StringUtils.trimToNull(" abc ") = "abc"
340      * </pre>
341      *
342      * @param str the String to be trimmed, may be null
343      * @return the trimmed String,
344      * <code>null</code> if only chars &lt;= 32, empty or null String input
345      * @since 2.0
346      */

347     public static String JavaDoc trimToNull(String JavaDoc str) {
348         String JavaDoc ts = trim(str);
349         return isEmpty(ts) ? null : ts;
350     }
351
352     /**
353      * <p>Removes control characters (char &lt;= 32) from both
354      * ends of this String returning an empty String ("") if the String
355      * is empty ("") after the trim or if it is <code>null</code>.
356      *
357      * <p>The String is trimmed using {@link String#trim()}.
358      * Trim removes start and end characters &lt;= 32.
359      * To strip whitespace use {@link #stripToEmpty(String)}.</p>
360      *
361      * <pre>
362      * StringUtils.trimToEmpty(null) = ""
363      * StringUtils.trimToEmpty("") = ""
364      * StringUtils.trimToEmpty(" ") = ""
365      * StringUtils.trimToEmpty("abc") = "abc"
366      * StringUtils.trimToEmpty(" abc ") = "abc"
367      * </pre>
368      *
369      * @param str the String to be trimmed, may be null
370      * @return the trimmed String, or an empty String if <code>null</code> input
371      * @since 2.0
372      */

373     public static String JavaDoc trimToEmpty(String JavaDoc str) {
374         return str == null ? EMPTY : str.trim();
375     }
376
377     // Stripping
378
//-----------------------------------------------------------------------
379
/**
380      * <p>Strips whitespace from the start and end of a String.</p>
381      *
382      * <p>This is similar to {@link #trim(String)} but removes whitespace.
383      * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
384      *
385      * <p>A <code>null</code> input String returns <code>null</code>.</p>
386      *
387      * <pre>
388      * StringUtils.strip(null) = null
389      * StringUtils.strip("") = ""
390      * StringUtils.strip(" ") = ""
391      * StringUtils.strip("abc") = "abc"
392      * StringUtils.strip(" abc") = "abc"
393      * StringUtils.strip("abc ") = "abc"
394      * StringUtils.strip(" abc ") = "abc"
395      * StringUtils.strip(" ab c ") = "ab c"
396      * </pre>
397      *
398      * @param str the String to remove whitespace from, may be null
399      * @return the stripped String, <code>null</code> if null String input
400      */

401     public static String JavaDoc strip(String JavaDoc str) {
402         return strip(str, null);
403     }
404
405     /**
406      * <p>Strips whitespace from the start and end of a String returning
407      * <code>null</code> if the String is empty ("") after the strip.</p>
408      *
409      * <p>This is similar to {@link #trimToNull(String)} but removes whitespace.
410      * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
411      *
412      * <pre>
413      * StringUtils.strip(null) = null
414      * StringUtils.strip("") = null
415      * StringUtils.strip(" ") = null
416      * StringUtils.strip("abc") = "abc"
417      * StringUtils.strip(" abc") = "abc"
418      * StringUtils.strip("abc ") = "abc"
419      * StringUtils.strip(" abc ") = "abc"
420      * StringUtils.strip(" ab c ") = "ab c"
421      * </pre>
422      *
423      * @param str the String to be stripped, may be null
424      * @return the stripped String,
425      * <code>null</code> if whitespace, empty or null String input
426      * @since 2.0
427      */

428     public static String JavaDoc stripToNull(String JavaDoc str) {
429         if (str == null) {
430             return null;
431         }
432         str = strip(str, null);
433         return str.length() == 0 ? null : str;
434     }
435
436     /**
437      * <p>Strips whitespace from the start and end of a String returning
438      * an empty String if <code>null</code> input.</p>
439      *
440      * <p>This is similar to {@link #trimToEmpty(String)} but removes whitespace.
441      * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
442      *
443      * <pre>
444      * StringUtils.strip(null) = ""
445      * StringUtils.strip("") = ""
446      * StringUtils.strip(" ") = ""
447      * StringUtils.strip("abc") = "abc"
448      * StringUtils.strip(" abc") = "abc"
449      * StringUtils.strip("abc ") = "abc"
450      * StringUtils.strip(" abc ") = "abc"
451      * StringUtils.strip(" ab c ") = "ab c"
452      * </pre>
453      *
454      * @param str the String to be stripped, may be null
455      * @return the trimmed String, or an empty String if <code>null</code> input
456      * @since 2.0
457      */

458     public static String JavaDoc stripToEmpty(String JavaDoc str) {
459         return str == null ? EMPTY : strip(str, null);
460     }
461
462     /**
463      * <p>Strips any of a set of characters from the start and end of a String.
464      * This is similar to {@link String#trim()} but allows the characters
465      * to be stripped to be controlled.</p>
466      *
467      * <p>A <code>null</code> input String returns <code>null</code>.
468      * An empty string ("") input returns the empty string.</p>
469      *
470      * <p>If the stripChars String is <code>null</code>, whitespace is
471      * stripped as defined by {@link Character#isWhitespace(char)}.
472      * Alternatively use {@link #strip(String)}.</p>
473      *
474      * <pre>
475      * StringUtils.strip(null, *) = null
476      * StringUtils.strip("", *) = ""
477      * StringUtils.strip("abc", null) = "abc"
478      * StringUtils.strip(" abc", null) = "abc"
479      * StringUtils.strip("abc ", null) = "abc"
480      * StringUtils.strip(" abc ", null) = "abc"
481      * StringUtils.strip(" abcyx", "xyz") = " abc"
482      * </pre>
483      *
484      * @param str the String to remove characters from, may be null
485      * @param stripChars the characters to remove, null treated as whitespace
486      * @return the stripped String, <code>null</code> if null String input
487      */

488     public static String JavaDoc strip(String JavaDoc str, String JavaDoc stripChars) {
489         if (isEmpty(str)) {
490             return str;
491         }
492         str = stripStart(str, stripChars);
493         return stripEnd(str, stripChars);
494     }
495
496     /**
497      * <p>Strips any of a set of characters from the start of a String.</p>
498      *
499      * <p>A <code>null</code> input String returns <code>null</code>.
500      * An empty string ("") input returns the empty string.</p>
501      *
502      * <p>If the stripChars String is <code>null</code>, whitespace is
503      * stripped as defined by {@link Character#isWhitespace(char)}.</p>
504      *
505      * <pre>
506      * StringUtils.stripStart(null, *) = null
507      * StringUtils.stripStart("", *) = ""
508      * StringUtils.stripStart("abc", "") = "abc"
509      * StringUtils.stripStart("abc", null) = "abc"
510      * StringUtils.stripStart(" abc", null) = "abc"
511      * StringUtils.stripStart("abc ", null) = "abc "
512      * StringUtils.stripStart(" abc ", null) = "abc "
513      * StringUtils.stripStart("yxabc ", "xyz") = "abc "
514      * </pre>
515      *
516      * @param str the String to remove characters from, may be null
517      * @param stripChars the characters to remove, null treated as whitespace
518      * @return the stripped String, <code>null</code> if null String input
519      */

520     public static String JavaDoc stripStart(String JavaDoc str, String JavaDoc stripChars) {
521         int strLen;
522         if (str == null || (strLen = str.length()) == 0) {
523             return str;
524         }
525         int start = 0;
526         if (stripChars == null) {
527             while ((start != strLen) && Character.isWhitespace(str.charAt(start))) {
528                 start++;
529             }
530         } else if (stripChars.length() == 0) {
531             return str;
532         } else {
533             while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != -1)) {
534                 start++;
535             }
536         }
537         return str.substring(start);
538     }
539
540     /**
541      * <p>Strips any of a set of characters from the end of a String.</p>
542      *
543      * <p>A <code>null</code> input String returns <code>null</code>.
544      * An empty string ("") input returns the empty string.</p>
545      *
546      * <p>If the stripChars String is <code>null</code>, whitespace is
547      * stripped as defined by {@link Character#isWhitespace(char)}.</p>
548      *
549      * <pre>
550      * StringUtils.stripEnd(null, *) = null
551      * StringUtils.stripEnd("", *) = ""
552      * StringUtils.stripEnd("abc", "") = "abc"
553      * StringUtils.stripEnd("abc", null) = "abc"
554      * StringUtils.stripEnd(" abc", null) = " abc"
555      * StringUtils.stripEnd("abc ", null) = "abc"
556      * StringUtils.stripEnd(" abc ", null) = " abc"
557      * StringUtils.stripEnd(" abcyx", "xyz") = " abc"
558      * </pre>
559      *
560      * @param str the String to remove characters from, may be null
561      * @param stripChars the characters to remove, null treated as whitespace
562      * @return the stripped String, <code>null</code> if null String input
563      */

564     public static String JavaDoc stripEnd(String JavaDoc str, String JavaDoc stripChars) {
565         int end;
566         if (str == null || (end = str.length()) == 0) {
567             return str;
568         }
569
570         if (stripChars == null) {
571             while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) {
572                 end--;
573             }
574         } else if (stripChars.length() == 0) {
575             return str;
576         } else {
577             while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != -1)) {
578                 end--;
579             }
580         }
581         return str.substring(0, end);
582     }
583
584     // StripAll
585
//-----------------------------------------------------------------------
586
/**
587      * <p>Strips whitespace from the start and end of every String in an array.
588      * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
589      *
590      * <p>A new array is returned each time, except for length zero.
591      * A <code>null</code> array will return <code>null</code>.
592      * An empty array will return itself.
593      * A <code>null</code> array entry will be ignored.</p>
594      *
595      * <pre>
596      * StringUtils.stripAll(null) = null
597      * StringUtils.stripAll([]) = []
598      * StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"]
599      * StringUtils.stripAll(["abc ", null]) = ["abc", null]
600      * </pre>
601      *
602      * @param strs the array to remove whitespace from, may be null
603      * @return the stripped Strings, <code>null</code> if null array input
604      */

605     public static String JavaDoc[] stripAll(String JavaDoc[] strs) {
606         return stripAll(strs, null);
607     }
608
609     /**
610      * <p>Strips any of a set of characters from the start and end of every
611      * String in an array.</p>
612      * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
613      *
614      * <p>A new array is returned each time, except for length zero.
615      * A <code>null</code> array will return <code>null</code>.
616      * An empty array will return itself.
617      * A <code>null</code> array entry will be ignored.
618      * A <code>null</code> stripChars will strip whitespace as defined by
619      * {@link Character#isWhitespace(char)}.</p>
620      *
621      * <pre>
622      * StringUtils.stripAll(null, *) = null
623      * StringUtils.stripAll([], *) = []
624      * StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"]
625      * StringUtils.stripAll(["abc ", null], null) = ["abc", null]
626      * StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null]
627      * StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null]
628      * </pre>
629      *
630      * @param strs the array to remove characters from, may be null
631      * @param stripChars the characters to remove, null treated as whitespace
632      * @return the stripped Strings, <code>null</code> if null array input
633      */

634     public static String JavaDoc[] stripAll(String JavaDoc[] strs, String JavaDoc stripChars) {
635         int strsLen;
636         if (strs == null || (strsLen = strs.length) == 0) {
637             return strs;
638         }
639         String JavaDoc[] newArr = new String JavaDoc[strsLen];
640         for (int i = 0; i < strsLen; i++) {
641             newArr[i] = strip(strs[i], stripChars);
642         }
643         return newArr;
644     }
645
646     // Equals
647
//-----------------------------------------------------------------------
648
/**
649      * <p>Compares two Strings, returning <code>true</code> if they are equal.</p>
650      *
651      * <p><code>null</code>s are handled without exceptions. Two <code>null</code>
652      * references are considered to be equal. The comparison is case sensitive.</p>
653      *
654      * <pre>
655      * StringUtils.equals(null, null) = true
656      * StringUtils.equals(null, "abc") = false
657      * StringUtils.equals("abc", null) = false
658      * StringUtils.equals("abc", "abc") = true
659      * StringUtils.equals("abc", "ABC") = false
660      * </pre>
661      *
662      * @see java.lang.String#equals(Object)
663      * @param str1 the first String, may be null
664      * @param str2 the second String, may be null
665      * @return <code>true</code> if the Strings are equal, case sensitive, or
666      * both <code>null</code>
667      */

668     public static boolean equals(String JavaDoc str1, String JavaDoc str2) {
669         return str1 == null ? str2 == null : str1.equals(str2);
670     }
671
672     /**
673      * <p>Compares two Strings, returning <code>true</code> if they are equal ignoring
674      * the case.</p>
675      *
676      * <p><code>null</code>s are handled without exceptions. Two <code>null</code>
677      * references are considered equal. Comparison is case insensitive.</p>
678      *
679      * <pre>
680      * StringUtils.equalsIgnoreCase(null, null) = true
681      * StringUtils.equalsIgnoreCase(null, "abc") = false
682      * StringUtils.equalsIgnoreCase("abc", null) = false
683      * StringUtils.equalsIgnoreCase("abc", "abc") = true
684      * StringUtils.equalsIgnoreCase("abc", "ABC") = true
685      * </pre>
686      *
687      * @see java.lang.String#equalsIgnoreCase(String)
688      * @param str1 the first String, may be null
689      * @param str2 the second String, may be null
690      * @return <code>true</code> if the Strings are equal, case insensitive, or
691      * both <code>null</code>
692      */

693     public static boolean equalsIgnoreCase(String JavaDoc str1, String JavaDoc str2) {
694         return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
695     }
696
697     // IndexOf
698
//-----------------------------------------------------------------------
699
/**
700      * <p>Finds the first index within a String, handling <code>null</code>.
701      * This method uses {@link String#indexOf(int)}.</p>
702      *
703      * <p>A <code>null</code> or empty ("") String will return <code>-1</code>.</p>
704      *
705      * <pre>
706      * StringUtils.indexOf(null, *) = -1
707      * StringUtils.indexOf("", *) = -1
708      * StringUtils.indexOf("aabaabaa", 'a') = 0
709      * StringUtils.indexOf("aabaabaa", 'b') = 2
710      * </pre>
711      *
712      * @param str the String to check, may be null
713      * @param searchChar the character to find
714      * @return the first index of the search character,
715      * -1 if no match or <code>null</code> string input
716      * @since 2.0
717      */

718     public static int indexOf(String JavaDoc str, char searchChar) {
719         if (isEmpty(str)) {
720             return -1;
721         }
722         return str.indexOf(searchChar);
723     }
724
725     /**
726      * <p>Finds the first index within a String from a start position,
727      * handling <code>null</code>.
728      * This method uses {@link String#indexOf(int, int)}.</p>
729      *
730      * <p>A <code>null</code> or empty ("") String will return <code>-1</code>.
731      * A negative start position is treated as zero.
732      * A start position greater than the string length returns <code>-1</code>.</p>
733      *
734      * <pre>
735      * StringUtils.indexOf(null, *, *) = -1
736      * StringUtils.indexOf("", *, *) = -1
737      * StringUtils.indexOf("aabaabaa", 'b', 0) = 2
738      * StringUtils.indexOf("aabaabaa", 'b', 3) = 5
739      * StringUtils.indexOf("aabaabaa", 'b', 9) = -1
740      * StringUtils.indexOf("aabaabaa", 'b', -1) = 2
741      * </pre>
742      *
743      * @param str the String to check, may be null
744      * @param searchChar the character to find
745      * @param startPos the start position, negative treated as zero
746      * @return the first index of the search character,
747      * -1 if no match or <code>null</code> string input
748      * @since 2.0
749      */

750     public static int indexOf(String JavaDoc str, char searchChar, int startPos) {
751         if (isEmpty(str)) {
752             return -1;
753         }
754         return str.indexOf(searchChar, startPos);
755     }
756
757     /**
758      * <p>Finds the first index within a String, handling <code>null</code>.
759      * This method uses {@link String#indexOf(String)}.</p>
760      *
761      * <p>A <code>null</code> String will return <code>-1</code>.</p>
762      *
763      * <pre>
764      * StringUtils.indexOf(null, *) = -1
765      * StringUtils.indexOf(*, null) = -1
766      * StringUtils.indexOf("", "") = 0
767      * StringUtils.indexOf("aabaabaa", "a") = 0
768      * StringUtils.indexOf("aabaabaa", "b") = 2
769      * StringUtils.indexOf("aabaabaa", "ab") = 1
770      * StringUtils.indexOf("aabaabaa", "") = 0
771      * </pre>
772      *
773      * @param str the String to check, may be null
774      * @param searchStr the String to find, may be null
775      * @return the first index of the search String,
776      * -1 if no match or <code>null</code> string input
777      * @since 2.0
778      */

779     public static int indexOf(String JavaDoc str, String JavaDoc searchStr) {
780         if (str == null || searchStr == null) {
781             return -1;
782         }
783         return str.indexOf(searchStr);
784     }
785
786     /**
787      * <p>Finds the n-th index within a String, handling <code>null</code>.
788      * This method uses {@link String#indexOf(String)}.</p>
789      *
790      * <p>A <code>null</code> String will return <code>-1</code>.</p>
791      *
792      * <pre>
793      * StringUtils.ordinalIndexOf(null, *, *) = -1
794      * StringUtils.ordinalIndexOf(*, null, *) = -1
795      * StringUtils.ordinalIndexOf("", "", *) = 0
796      * StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0
797      * StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1
798      * StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2
799      * StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5
800      * StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
801      * StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
802      * StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0
803      * StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0
804      * </pre>
805      *
806      * @param str the String to check, may be null
807      * @param searchStr the String to find, may be null
808      * @param ordinal the n-th <code>searchStr</code> to find
809      * @return the n-th index of the search String,
810      * <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input
811      * @since 2.1
812      */

813     public static int ordinalIndexOf(String JavaDoc str, String JavaDoc searchStr, int ordinal) {
814         if (str == null || searchStr == null || ordinal <= 0) {
815             return INDEX_NOT_FOUND;
816         }
817         if (searchStr.length() == 0) {
818             return 0;
819         }
820         int found = 0;
821         int index = INDEX_NOT_FOUND;
822         do {
823             index = str.indexOf(searchStr, index + 1);
824             if (index < 0) {
825                 return index;
826             }
827             found++;
828         } while (found < ordinal);
829         return index;
830     }
831
832     /**
833      * <p>Finds the first index within a String, handling <code>null</code>.
834      * This method uses {@link String#indexOf(String, int)}.</p>
835      *
836      * <p>A <code>null</code> String will return <code>-1</code>.
837      * A negative start position is treated as zero.
838      * An empty ("") search String always matches.
839      * A start position greater than the string length only matches
840      * an empty search String.</p>
841      *
842      * <pre>
843      * StringUtils.indexOf(null, *, *) = -1
844      * StringUtils.indexOf(*, null, *) = -1
845      * StringUtils.indexOf("", "", 0) = 0
846      * StringUtils.indexOf("aabaabaa", "a", 0) = 0
847      * StringUtils.indexOf("aabaabaa", "b", 0) = 2
848      * StringUtils.indexOf("aabaabaa", "ab", 0) = 1
849      * StringUtils.indexOf("aabaabaa", "b", 3) = 5
850      * StringUtils.indexOf("aabaabaa", "b", 9) = -1
851      * StringUtils.indexOf("aabaabaa", "b", -1) = 2
852      * StringUtils.indexOf("aabaabaa", "", 2) = 2
853      * StringUtils.indexOf("abc", "", 9) = 3
854      * </pre>
855      *
856      * @param str the String to check, may be null
857      * @param searchStr the String to find, may be null
858      * @param startPos the start position, negative treated as zero
859      * @return the first index of the search String,
860      * -1 if no match or <code>null</code> string input
861      * @since 2.0
862      */

863     public static int indexOf(String JavaDoc str, String JavaDoc searchStr, int startPos) {
864         if (str == null || searchStr == null) {
865             return -1;
866         }
867         // JDK1.2/JDK1.3 have a bug, when startPos > str.length for "", hence
868
if (searchStr.length() == 0 && startPos >= str.length()) {
869             return str.length();
870         }
871         return str.indexOf(searchStr, startPos);
872     }
873
874     // LastIndexOf
875
//-----------------------------------------------------------------------
876
/**
877      * <p>Finds the last index within a String, handling <code>null</code>.
878      * This method uses {@link String#lastIndexOf(int)}.</p>
879      *
880      * <p>A <code>null</code> or empty ("") String will return <code>-1</code>.</p>
881      *
882      * <pre>
883      * StringUtils.lastIndexOf(null, *) = -1
884      * StringUtils.lastIndexOf("", *) = -1
885      * StringUtils.lastIndexOf("aabaabaa", 'a') = 7
886      * StringUtils.lastIndexOf("aabaabaa", 'b') = 5
887      * </pre>
888      *
889      * @param str the String to check, may be null
890      * @param searchChar the character to find
891      * @return the last index of the search character,
892      * -1 if no match or <code>null</code> string input
893      * @since 2.0
894      */

895     public static int lastIndexOf(String JavaDoc str, char searchChar) {
896         if (isEmpty(str)) {
897             return -1;
898         }
899         return str.lastIndexOf(searchChar);
900     }
901
902     /**
903      * <p>Finds the last index within a String from a start position,
904      * handling <code>null</code>.
905      * This method uses {@link String#lastIndexOf(int, int)}.</p>
906      *
907      * <p>A <code>null</code> or empty ("") String will return <code>-1</code>.
908      * A negative start position returns <code>-1</code>.
909      * A start position greater than the string length searches the whole string.</p>
910      *
911      * <pre>
912      * StringUtils.lastIndexOf(null, *, *) = -1
913      * StringUtils.lastIndexOf("", *, *) = -1
914      * StringUtils.lastIndexOf("aabaabaa", 'b', 8) = 5
915      * StringUtils.lastIndexOf("aabaabaa", 'b', 4) = 2
916      * StringUtils.lastIndexOf("aabaabaa", 'b', 0) = -1
917      * StringUtils.lastIndexOf("aabaabaa", 'b', 9) = 5
918      * StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
919      * StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0
920      * </pre>
921      *
922      * @param str the String to check, may be null
923      * @param searchChar the character to find
924      * @param startPos the start position
925      * @return the last index of the search character,
926      * -1 if no match or <code>null</code> string input
927      * @since 2.0
928      */

929     public static int lastIndexOf(String JavaDoc str, char searchChar, int startPos) {
930         if (isEmpty(str)) {
931             return -1;
932         }
933         return str.lastIndexOf(searchChar, startPos);
934     }
935
936     /**
937      * <p>Finds the last index within a String, handling <code>null</code>.
938      * This method uses {@link String#lastIndexOf(String)}.</p>
939      *
940      * <p>A <code>null</code> String will return <code>-1</code>.</p>
941      *
942      * <pre>
943      * StringUtils.lastIndexOf(null, *) = -1
944      * StringUtils.lastIndexOf(*, null) = -1
945      * StringUtils.lastIndexOf("", "") = 0
946      * StringUtils.lastIndexOf("aabaabaa", "a") = 0
947      * StringUtils.lastIndexOf("aabaabaa", "b") = 2
948      * StringUtils.lastIndexOf("aabaabaa", "ab") = 1
949      * StringUtils.lastIndexOf("aabaabaa", "") = 8
950      * </pre>
951      *
952      * @param str the String to check, may be null
953      * @param searchStr the String to find, may be null
954      * @return the last index of the search String,
955      * -1 if no match or <code>null</code> string input
956      * @since 2.0
957      */

958     public static int lastIndexOf(String JavaDoc str, String JavaDoc searchStr) {
959         if (str == null || searchStr == null) {
960             return -1;
961         }
962         return str.lastIndexOf(searchStr);
963     }
964
965     /**
966      * <p>Finds the first index within a String, handling <code>null</code>.
967      * This method uses {@link String#lastIndexOf(String, int)}.</p>
968      *
969      * <p>A <code>null</code> String will return <code>-1</code>.
970      * A negative start position returns <code>-1</code>.
971      * An empty ("") search String always matches unless the start position is negative.
972      * A start position greater than the string length searches the whole string.</p>
973      *
974      * <pre>
975      * StringUtils.lastIndexOf(null, *, *) = -1
976      * StringUtils.lastIndexOf(*, null, *) = -1
977      * StringUtils.lastIndexOf("aabaabaa", "a", 8) = 7
978      * StringUtils.lastIndexOf("aabaabaa", "b", 8) = 5
979      * StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
980      * StringUtils.lastIndexOf("aabaabaa", "b", 9) = 5
981      * StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
982      * StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0
983      * StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1
984      * </pre>
985      *
986      * @param str the String to check, may be null
987      * @param searchStr the String to find, may be null
988      * @param startPos the start position, negative treated as zero
989      * @return the first index of the search String,
990      * -1 if no match or <code>null</code> string input
991      * @since 2.0
992      */

993     public static int lastIndexOf(String JavaDoc str, String JavaDoc searchStr, int startPos) {
994         if (str == null || searchStr == null) {
995             return -1;
996         }
997         return str.lastIndexOf(searchStr, startPos);
998     }
999
1000    // Contains
1001
//-----------------------------------------------------------------------
1002
/**
1003     * <p>Checks if String contains a search character, handling <code>null</code>.
1004     * This method uses {@link String#indexOf(int)}.</p>
1005     *
1006     * <p>A <code>null</code> or empty ("") String will return <code>false</code>.</p>
1007     *
1008     * <pre>
1009     * StringUtils.contains(null, *) = false
1010     * StringUtils.contains("", *) = false
1011     * StringUtils.contains("abc", 'a') = true
1012     * StringUtils.contains("abc", 'z') = false
1013     * </pre>
1014     *
1015     * @param str the String to check, may be null
1016     * @param searchChar the character to find
1017     * @return true if the String contains the search character,
1018     * false if not or <code>null</code> string input
1019     * @since 2.0
1020     */

1021    public static boolean contains(String JavaDoc str, char searchChar) {
1022        if (isEmpty(str)) {
1023            return false;
1024        }
1025        return str.indexOf(searchChar) >= 0;
1026    }
1027
1028    /**
1029     * <p>Checks if String contains a search String, handling <code>null</code>.
1030     * This method uses {@link String#indexOf(int)}.</p>
1031     *
1032     * <p>A <code>null</code> String will return <code>false</code>.</p>
1033     *
1034     * <pre>
1035     * StringUtils.contains(null, *) = false
1036     * StringUtils.contains(*, null) = false
1037     * StringUtils.contains("", "") = true
1038     * StringUtils.contains("abc", "") = true
1039     * StringUtils.contains("abc", "a") = true
1040     * StringUtils.contains("abc", "z") = false
1041     * </pre>
1042     *
1043     * @param str the String to check, may be null
1044     * @param searchStr the String to find, may be null
1045     * @return true if the String contains the search String,
1046     * false if not or <code>null</code> string input
1047     * @since 2.0
1048     */

1049    public static boolean contains(String JavaDoc str, String JavaDoc searchStr) {
1050        if (str == null || searchStr == null) {
1051            return false;
1052        }
1053        return str.indexOf(searchStr) >= 0;
1054    }
1055
1056    // IndexOfAny chars
1057
//-----------------------------------------------------------------------
1058
/**
1059     * <p>Search a String to find the first index of any
1060     * character in the given set of characters.</p>
1061     *
1062     * <p>A <code>null</code> String will return <code>-1</code>.
1063     * A <code>null</code> or zero length search array will return <code>-1</code>.</p>
1064     *
1065     * <pre>
1066     * StringUtils.indexOfAny(null, *) = -1
1067     * StringUtils.indexOfAny("", *) = -1
1068     * StringUtils.indexOfAny(*, null) = -1
1069     * StringUtils.indexOfAny(*, []) = -1
1070     * StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0
1071     * StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
1072     * StringUtils.indexOfAny("aba", ['z']) = -1
1073     * </pre>
1074     *
1075     * @param str the String to check, may be null
1076     * @param searchChars the chars to search for, may be null
1077     * @return the index of any of the chars, -1 if no match or null input
1078     * @since 2.0
1079     */

1080    public static int indexOfAny(String JavaDoc str, char[] searchChars) {
1081        if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
1082            return -1;
1083        }
1084        for (int i = 0; i < str.length(); i++) {
1085            char ch = str.charAt(i);
1086            for (int j = 0; j < searchChars.length; j++) {
1087                if (searchChars[j] == ch) {
1088                    return i;
1089                }
1090            }
1091        }
1092        return -1;
1093    }
1094
1095    /**
1096     * <p>Search a String to find the first index of any
1097     * character in the given set of characters.</p>
1098     *
1099     * <p>A <code>null</code> String will return <code>-1</code>.
1100     * A <code>null</code> search string will return <code>-1</code>.</p>
1101     *
1102     * <pre>
1103     * StringUtils.indexOfAny(null, *) = -1
1104     * StringUtils.indexOfAny("", *) = -1
1105     * StringUtils.indexOfAny(*, null) = -1
1106     * StringUtils.indexOfAny(*, "") = -1
1107     * StringUtils.indexOfAny("zzabyycdxx", "za") = 0
1108     * StringUtils.indexOfAny("zzabyycdxx", "by") = 3
1109     * StringUtils.indexOfAny("aba","z") = -1
1110     * </pre>
1111     *
1112     * @param str the String to check, may be null
1113     * @param searchChars the chars to search for, may be null
1114     * @return the index of any of the chars, -1 if no match or null input
1115     * @since 2.0
1116     */

1117    public static int indexOfAny(String JavaDoc str, String JavaDoc searchChars) {
1118        if (isEmpty(str) || isEmpty(searchChars)) {
1119            return -1;
1120        }
1121        return indexOfAny(str, searchChars.toCharArray());
1122    }
1123
1124    // IndexOfAnyBut chars
1125
//-----------------------------------------------------------------------
1126
/**
1127     * <p>Search a String to find the first index of any
1128     * character not in the given set of characters.</p>
1129     *
1130     * <p>A <code>null</code> String will return <code>-1</code>.
1131     * A <code>null</code> or zero length search array will return <code>-1</code>.</p>
1132     *
1133     * <pre>
1134     * StringUtils.indexOfAnyBut(null, *) = -1
1135     * StringUtils.indexOfAnyBut("", *) = -1
1136     * StringUtils.indexOfAnyBut(*, null) = -1
1137     * StringUtils.indexOfAnyBut(*, []) = -1
1138     * StringUtils.indexOfAnyBut("zzabyycdxx",'za') = 3
1139     * StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0
1140     * StringUtils.indexOfAnyBut("aba", 'ab') = -1
1141     * </pre>
1142     *
1143     * @param str the String to check, may be null
1144     * @param searchChars the chars to search for, may be null
1145     * @return the index of any of the chars, -1 if no match or null input
1146     * @since 2.0
1147     */

1148    public static int indexOfAnyBut(String JavaDoc str, char[] searchChars) {
1149        if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
1150            return -1;
1151        }
1152        outer : for (int i = 0; i < str.length(); i++) {
1153            char ch = str.charAt(i);
1154            for (int j = 0; j < searchChars.length; j++) {
1155                if (searchChars[j] == ch) {
1156                    continue outer;
1157                }
1158            }
1159            return i;
1160        }
1161        return -1;
1162    }
1163
1164    /**
1165     * <p>Search a String to find the first index of any
1166     * character not in the given set of characters.</p>
1167     *
1168     * <p>A <code>null</code> String will return <code>-1</code>.
1169     * A <code>null</code> search string will return <code>-1</code>.</p>
1170     *
1171     * <pre>
1172     * StringUtils.indexOfAnyBut(null, *) = -1
1173     * StringUtils.indexOfAnyBut("", *) = -1
1174     * StringUtils.indexOfAnyBut(*, null) = -1
1175     * StringUtils.indexOfAnyBut(*, "") = -1
1176     * StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
1177     * StringUtils.indexOfAnyBut("zzabyycdxx", "") = 0
1178     * StringUtils.indexOfAnyBut("aba","ab") = -1
1179     * </pre>
1180     *
1181     * @param str the String to check, may be null
1182     * @param searchChars the chars to search for, may be null
1183     * @return the index of any of the chars, -1 if no match or null input
1184     * @since 2.0
1185     */

1186    public static int indexOfAnyBut(String JavaDoc str, String JavaDoc searchChars) {
1187        if (isEmpty(str) || isEmpty(searchChars)) {
1188            return -1;
1189        }
1190        for (int i = 0; i < str.length(); i++) {
1191            if (searchChars.indexOf(str.charAt(i)) < 0) {
1192                return i;
1193            }
1194        }
1195        return -1;
1196    }
1197
1198    // ContainsOnly
1199
//-----------------------------------------------------------------------
1200
/**
1201     * <p>Checks if the String contains only certain characters.</p>
1202     *
1203     * <p>A <code>null</code> String will return <code>false</code>.
1204     * A <code>null</code> valid character array will return <code>false</code>.
1205     * An empty String ("") always returns <code>true</code>.</p>
1206     *
1207     * <pre>
1208     * StringUtils.containsOnly(null, *) = false
1209     * StringUtils.containsOnly(*, null) = false
1210     * StringUtils.containsOnly("", *) = true
1211     * StringUtils.containsOnly("ab", '') = false
1212     * StringUtils.containsOnly("abab", 'abc') = true
1213     * StringUtils.containsOnly("ab1", 'abc') = false
1214     * StringUtils.containsOnly("abz", 'abc') = false
1215     * </pre>
1216     *
1217     * @param str the String to check, may be null
1218     * @param valid an array of valid chars, may be null
1219     * @return true if it only contains valid chars and is non-null
1220     */

1221    public static boolean containsOnly(String JavaDoc str, char[] valid) {
1222        // All these pre-checks are to maintain API with an older version
1223
if ((valid == null) || (str == null)) {
1224            return false;
1225        }
1226        if (str.length() == 0) {
1227            return true;
1228        }
1229        if (valid.length == 0) {
1230            return false;
1231        }
1232        return indexOfAnyBut(str, valid) == -1;
1233    }
1234
1235    /**
1236     * <p>Checks if the String contains only certain characters.</p>
1237     *
1238     * <p>A <code>null</code> String will return <code>false</code>.
1239     * A <code>null</code> valid character String will return <code>false</code>.
1240     * An empty String ("") always returns <code>true</code>.</p>
1241     *
1242     * <pre>
1243     * StringUtils.containsOnly(null, *) = false
1244     * StringUtils.containsOnly(*, null) = false
1245     * StringUtils.containsOnly("", *) = true
1246     * StringUtils.containsOnly("ab", "") = false
1247     * StringUtils.containsOnly("abab", "abc") = true
1248     * StringUtils.containsOnly("ab1", "abc") = false
1249     * StringUtils.containsOnly("abz", "abc") = false
1250     * </pre>
1251     *
1252     * @param str the String to check, may be null
1253     * @param validChars a String of valid chars, may be null
1254     * @return true if it only contains valid chars and is non-null
1255     * @since 2.0
1256     */

1257    public static boolean containsOnly(String JavaDoc str, String JavaDoc validChars) {
1258        if (str == null || validChars == null) {
1259            return false;
1260        }
1261        return containsOnly(str, validChars.toCharArray());
1262    }
1263
1264    // ContainsNone
1265
//-----------------------------------------------------------------------
1266
/**
1267     * <p>Checks that the String does not contain certain characters.</p>
1268     *
1269     * <p>A <code>null</code> String will return <code>true</code>.
1270     * A <code>null</code> invalid character array will return <code>true</code>.
1271     * An empty String ("") always returns true.</p>
1272     *
1273     * <pre>
1274     * StringUtils.containsNone(null, *) = true
1275     * StringUtils.containsNone(*, null) = true
1276     * StringUtils.containsNone("", *) = true
1277     * StringUtils.containsNone("ab", '') = true
1278     * StringUtils.containsNone("abab", 'xyz') = true
1279     * StringUtils.containsNone("ab1", 'xyz') = true
1280     * StringUtils.containsNone("abz", 'xyz') = false
1281     * </pre>
1282     *
1283     * @param str the String to check, may be null
1284     * @param invalidChars an array of invalid chars, may be null
1285     * @return true if it contains none of the invalid chars, or is null
1286     * @since 2.0
1287     */

1288    public static boolean containsNone(String JavaDoc str, char[] invalidChars) {
1289        if (str == null || invalidChars == null) {
1290            return true;
1291        }
1292        int strSize = str.length();
1293        int validSize = invalidChars.length;
1294        for (int i = 0; i < strSize; i++) {
1295            char ch = str.charAt(i);
1296            for (int j = 0; j < validSize; j++) {
1297                if (invalidChars[j] == ch) {
1298                    return false;
1299                }
1300            }
1301        }
1302        return true;
1303    }
1304
1305    /**
1306     * <p>Checks that the String does not contain certain characters.</p>
1307     *
1308     * <p>A <code>null</code> String will return <code>true</code>.
1309     * A <code>null</code> invalid character array will return <code>true</code>.
1310     * An empty String ("") always returns true.</p>
1311     *
1312     * <pre>
1313     * StringUtils.containsNone(null, *) = true
1314     * StringUtils.containsNone(*, null) = true
1315     * StringUtils.containsNone("", *) = true
1316     * StringUtils.containsNone("ab", "") = true
1317     * StringUtils.containsNone("abab", "xyz") = true
1318     * StringUtils.containsNone("ab1", "xyz") = true
1319     * StringUtils.containsNone("abz", "xyz") = false
1320     * </pre>
1321     *
1322     * @param str the String to check, may be null
1323     * @param invalidChars a String of invalid chars, may be null
1324     * @return true if it contains none of the invalid chars, or is null
1325     * @since 2.0
1326     */

1327    public static boolean containsNone(String JavaDoc str, String JavaDoc invalidChars) {
1328        if (str == null || invalidChars == null) {
1329            return true;
1330        }
1331        return containsNone(str, invalidChars.toCharArray());
1332    }
1333
1334    // IndexOfAny strings
1335
//-----------------------------------------------------------------------
1336
/**
1337     * <p>Find the first index of any of a set of potential substrings.</p>
1338     *
1339     * <p>A <code>null</code> String will return <code>-1</code>.
1340     * A <code>null</code> or zero length search array will return <code>-1</code>.
1341     * A <code>null</code> search array entry will be ignored, but a search
1342     * array containing "" will return <code>0</code> if <code>str</code> is not
1343     * null. This method uses {@link String#indexOf(String)}.</p>
1344     *
1345     * <pre>
1346     * StringUtils.indexOfAny(null, *) = -1
1347     * StringUtils.indexOfAny(*, null) = -1
1348     * StringUtils.indexOfAny(*, []) = -1
1349     * StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2
1350     * StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2
1351     * StringUtils.indexOfAny("zzabyycdxx", ["mn","op"]) = -1
1352     * StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
1353     * StringUtils.indexOfAny("zzabyycdxx", [""]) = 0
1354     * StringUtils.indexOfAny("", [""]) = 0
1355     * StringUtils.indexOfAny("", ["a"]) = -1
1356     * </pre>
1357     *
1358     * @param str the String to check, may be null
1359     * @param searchStrs the Strings to search for, may be null
1360     * @return the first index of any of the searchStrs in str, -1 if no match
1361     */

1362    public static int indexOfAny(String JavaDoc str, String JavaDoc[] searchStrs) {
1363        if ((str == null) || (searchStrs == null)) {
1364            return -1;
1365        }
1366        int sz = searchStrs.length;
1367
1368        // String's can't have a MAX_VALUEth index.
1369
int ret = Integer.MAX_VALUE;
1370
1371        int tmp = 0;
1372        for (int i = 0; i < sz; i++) {
1373            String JavaDoc search = searchStrs[i];
1374            if (search == null) {
1375                continue;
1376            }
1377            tmp = str.indexOf(search);
1378            if (tmp == -1) {
1379                continue;
1380            }
1381
1382            if (tmp < ret) {
1383                ret = tmp;
1384            }
1385        }
1386
1387        return (ret == Integer.MAX_VALUE) ? -1 : ret;
1388    }
1389
1390    /**
1391     * <p>Find the latest index of any of a set of potential substrings.</p>
1392     *
1393     * <p>A <code>null</code> String will return <code>-1</code>.
1394     * A <code>null</code> search array will return <code>-1</code>.
1395     * A <code>null</code> or zero length search array entry will be ignored,
1396     * but a search array containing "" will return the length of <code>str</code>
1397     * if <code>str</code> is not null. This method uses {@link String#indexOf(String)}</p>
1398     *
1399     * <pre>
1400     * StringUtils.lastIndexOfAny(null, *) = -1
1401     * StringUtils.lastIndexOfAny(*, null) = -1
1402     * StringUtils.lastIndexOfAny(*, []) = -1
1403     * StringUtils.lastIndexOfAny(*, [null]) = -1
1404     * StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
1405     * StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
1406     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
1407     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
1408     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""]) = 10
1409     * </pre>
1410     *
1411     * @param str the String to check, may be null
1412     * @param searchStrs the Strings to search for, may be null
1413     * @return the last index of any of the Strings, -1 if no match
1414     */

1415    public static int lastIndexOfAny(String JavaDoc str, String JavaDoc[] searchStrs) {
1416        if ((str == null) || (searchStrs == null)) {
1417            return -1;
1418        }
1419        int sz = searchStrs.length;
1420        int ret = -1;
1421        int tmp = 0;
1422        for (int i = 0; i < sz; i++) {
1423            String JavaDoc search = searchStrs[i];
1424            if (search == null) {
1425                continue;
1426            }
1427            tmp = str.lastIndexOf(search);
1428            if (tmp > ret) {
1429                ret = tmp;
1430            }
1431        }
1432        return ret;
1433    }
1434
1435    // Substring
1436
//-----------------------------------------------------------------------
1437
/**
1438     * <p>Gets a substring from the specified String avoiding exceptions.</p>
1439     *
1440     * <p>A negative start position can be used to start <code>n</code>
1441     * characters from the end of the String.</p>
1442     *
1443     * <p>A <code>null</code> String will return <code>null</code>.
1444     * An empty ("") String will return "".</p>
1445     *
1446     * <pre>
1447     * StringUtils.substring(null, *) = null
1448     * StringUtils.substring("", *) = ""
1449     * StringUtils.substring("abc", 0) = "abc"
1450     * StringUtils.substring("abc", 2) = "c"
1451     * StringUtils.substring("abc", 4) = ""
1452     * StringUtils.substring("abc", -2) = "bc"
1453     * StringUtils.substring("abc", -4) = "abc"
1454     * </pre>
1455     *
1456     * @param str the String to get the substring from, may be null
1457     * @param start the position to start from, negative means
1458     * count back from the end of the String by this many characters
1459     * @return substring from start position, <code>null</code> if null String input
1460     */

1461    public static String JavaDoc substring(String JavaDoc str, int start) {
1462        if (str == null) {
1463            return null;
1464        }
1465
1466        // handle negatives, which means last n characters
1467
if (start < 0) {
1468            start = str.length() + start; // remember start is negative
1469
}
1470
1471        if (start < 0) {
1472            start = 0;
1473        }
1474        if (start > str.length()) {
1475            return EMPTY;
1476        }
1477
1478        return str.substring(start);
1479    }
1480
1481    /**
1482     * <p>Gets a substring from the specified String avoiding exceptions.</p>
1483     *
1484     * <p>A negative start position can be used to start/end <code>n</code>
1485     * characters from the end of the String.</p>
1486     *
1487     * <p>The returned substring starts with the character in the <code>start</code>
1488     * position and ends before the <code>end</code> position. All position counting is
1489     * zero-based -- i.e., to start at the beginning of the string use
1490     * <code>start = 0</code>. Negative start and end positions can be used to
1491     * specify offsets relative to the end of the String.</p>
1492     *
1493     * <p>If <code>start</code> is not strictly to the left of <code>end</code>, ""
1494     * is returned.</p>
1495     *
1496     * <pre>
1497     * StringUtils.substring(null, *, *) = null
1498     * StringUtils.substring("", * , *) = "";
1499     * StringUtils.substring("abc", 0, 2) = "ab"
1500     * StringUtils.substring("abc", 2, 0) = ""
1501     * StringUtils.substring("abc", 2, 4) = "c"
1502     * StringUtils.substring("abc", 4, 6) = ""
1503     * StringUtils.substring("abc", 2, 2) = ""
1504     * StringUtils.substring("abc", -2, -1) = "b"
1505     * StringUtils.substring("abc", -4, 2) = "ab"
1506     * </pre>
1507     *
1508     * @param str the String to get the substring from, may be null
1509     * @param start the position to start from, negative means
1510     * count back from the end of the String by this many characters
1511     * @param end the position to end at (exclusive), negative means
1512     * count back from the end of the String by this many characters
1513     * @return substring from start position to end positon,
1514     * <code>null</code> if null String input
1515     */

1516    public static String JavaDoc substring(String JavaDoc str, int start, int end) {
1517        if (str == null) {
1518            return null;
1519        }
1520
1521        // handle negatives
1522
if (end < 0) {
1523            end = str.length() + end; // remember end is negative
1524
}
1525        if (start < 0) {
1526            start = str.length() + start; // remember start is negative
1527
}
1528
1529        // check length next
1530
if (end > str.length()) {
1531            end = str.length();
1532        }
1533
1534        // if start is greater than end, return ""
1535
if (start > end) {
1536            return EMPTY;
1537        }
1538
1539        if (start < 0) {
1540            start = 0;
1541        }
1542        if (end < 0) {
1543            end = 0;
1544        }
1545
1546        return str.substring(start, end);
1547    }
1548
1549    // Left/Right/Mid
1550
//-----------------------------------------------------------------------
1551
/**
1552     * <p>Gets the leftmost <code>len</code> characters of a String.</p>
1553     *
1554     * <p>If <code>len</code> characters are not available, or the
1555     * String is <code>null</code>, the String will be returned without
1556     * an exception. An exception is thrown if len is negative.</p>
1557     *
1558     * <pre>
1559     * StringUtils.left(null, *) = null
1560     * StringUtils.left(*, -ve) = ""
1561     * StringUtils.left("", *) = ""
1562     * StringUtils.left("abc", 0) = ""
1563     * StringUtils.left("abc", 2) = "ab"
1564     * StringUtils.left("abc", 4) = "abc"
1565     * </pre>
1566     *
1567     * @param str the String to get the leftmost characters from, may be null
1568     * @param len the length of the required String, must be zero or positive
1569     * @return the leftmost characters, <code>null</code> if null String input
1570     */

1571    public static String JavaDoc left(String JavaDoc str, int len) {
1572        if (str == null) {
1573            return null;
1574        }
1575        if (len < 0) {
1576            return EMPTY;
1577        }
1578        if (str.length() <= len) {
1579            return str;
1580        } else {
1581            return str.substring(0, len);
1582        }
1583    }
1584
1585    /**
1586     * <p>Gets the rightmost <code>len</code> characters of a String.</p>
1587     *
1588     * <p>If <code>len</code> characters are not available, or the String
1589     * is <code>null</code>, the String will be returned without an
1590     * an exception. An exception is thrown if len is negative.</p>
1591     *
1592     * <pre>
1593     * StringUtils.right(null, *) = null
1594     * StringUtils.right(*, -ve) = ""
1595     * StringUtils.right("", *) = ""
1596     * StringUtils.right("abc", 0) = ""
1597     * StringUtils.right("abc", 2) = "bc"
1598     * StringUtils.right("abc", 4) = "abc"
1599     * </pre>
1600     *
1601     * @param str the String to get the rightmost characters from, may be null
1602     * @param len the length of the required String, must be zero or positive
1603     * @return the rightmost characters, <code>null</code> if null String input
1604     */

1605    public static String JavaDoc right(String JavaDoc str, int len) {
1606        if (str == null) {
1607            return null;
1608        }
1609        if (len < 0) {
1610            return EMPTY;
1611        }
1612        if (str.length() <= len) {
1613            return str;
1614        } else {
1615            return str.substring(str.length() - len);
1616        }
1617    }
1618
1619    /**
1620     * <p>Gets <code>len</code> characters from the middle of a String.</p>
1621     *
1622     * <p>If <code>len</code> characters are not available, the remainder
1623     * of the String will be returned without an exception. If the
1624     * String is <code>null</code>, <code>null</code> will be returned.
1625     * An exception is thrown if len is negative.</p>
1626     *
1627     * <pre>
1628     * StringUtils.mid(null, *, *) = null
1629     * StringUtils.mid(*, *, -ve) = ""
1630     * StringUtils.mid("", 0, *) = ""
1631     * StringUtils.mid("abc", 0, 2) = "ab"
1632     * StringUtils.mid("abc", 0, 4) = "abc"
1633     * StringUtils.mid("abc", 2, 4) = "c"
1634     * StringUtils.mid("abc", 4, 2) = ""
1635     * StringUtils.mid("abc", -2, 2) = "ab"
1636     * </pre>
1637     *
1638     * @param str the String to get the characters from, may be null
1639     * @param pos the position to start from, negative treated as zero
1640     * @param len the length of the required String, must be zero or positive
1641     * @return the middle characters, <code>null</code> if null String input
1642     */

1643    public static String JavaDoc mid(String JavaDoc str, int pos, int len) {
1644        if (str == null) {
1645            return null;
1646        }
1647        if (len < 0 || pos > str.length()) {
1648            return EMPTY;
1649        }
1650        if (pos < 0) {
1651            pos = 0;
1652        }
1653        if (str.length() <= (pos + len)) {
1654            return str.substring(pos);
1655        } else {
1656            return str.substring(pos, pos + len);
1657        }
1658    }
1659
1660    // SubStringAfter/SubStringBefore
1661
//-----------------------------------------------------------------------
1662
/**
1663     * <p>Gets the substring before the first occurrence of a separator.
1664     * The separator is not returned.</p>
1665     *
1666     * <p>A <code>null</code> string input will return <code>null</code>.
1667     * An empty ("") string input will return the empty string.
1668     * A <code>null</code> separator will return the input string.</p>
1669     *
1670     * <pre>
1671     * StringUtils.substringBefore(null, *) = null
1672     * StringUtils.substringBefore("", *) = ""
1673     * StringUtils.substringBefore("abc", "a") = ""
1674     * StringUtils.substringBefore("abcba", "b") = "a"
1675     * StringUtils.substringBefore("abc", "c") = "ab"
1676     * StringUtils.substringBefore("abc", "d") = "abc"
1677     * StringUtils.substringBefore("abc", "") = ""
1678     * StringUtils.substringBefore("abc", null) = "abc"
1679     * </pre>
1680     *
1681     * @param str the String to get a substring from, may be null
1682     * @param separator the String to search for, may be null
1683     * @return the substring before the first occurrence of the separator,
1684     * <code>null</code> if null String input
1685     * @since 2.0
1686     */

1687    public static String JavaDoc substringBefore(String JavaDoc str, String JavaDoc separator) {
1688        if (isEmpty(str) || separator == null) {
1689            return str;
1690        }
1691        if (separator.length() == 0) {
1692            return EMPTY;
1693        }
1694        int pos = str.indexOf(separator);
1695        if (pos == -1) {
1696            return str;
1697        }
1698        return str.substring(0, pos);
1699    }
1700
1701    /**
1702     * <p>Gets the substring after the first occurrence of a separator.
1703     * The separator is not returned.</p>
1704     *
1705     * <p>A <code>null</code> string input will return <code>null</code>.
1706     * An empty ("") string input will return the empty string.
1707     * A <code>null</code> separator will return the empty string if the
1708     * input string is not <code>null</code>.</p>
1709     *
1710     * <pre>
1711     * StringUtils.substringAfter(null, *) = null
1712     * StringUtils.substringAfter("", *) = ""
1713     * StringUtils.substringAfter(*, null) = ""
1714     * StringUtils.substringAfter("abc", "a") = "bc"
1715     * StringUtils.substringAfter("abcba", "b") = "cba"
1716     * StringUtils.substringAfter("abc", "c") = ""
1717     * StringUtils.substringAfter("abc", "d") = ""
1718     * StringUtils.substringAfter("abc", "") = "abc"
1719     * </pre>
1720     *
1721     * @param str the String to get a substring from, may be null
1722     * @param separator the String to search for, may be null
1723     * @return the substring after the first occurrence of the separator,
1724     * <code>null</code> if null String input
1725     * @since 2.0
1726     */

1727    public static String JavaDoc substringAfter(String JavaDoc str, String JavaDoc separator) {
1728        if (isEmpty(str)) {
1729            return str;
1730        }
1731        if (separator == null) {
1732            return EMPTY;
1733        }
1734        int pos = str.indexOf(separator);
1735        if (pos == -1) {
1736            return EMPTY;
1737        }
1738        return str.substring(pos + separator.length());
1739    }
1740
1741    /**
1742     * <p>Gets the substring before the last occurrence of a separator.
1743     * The separator is not returned.</p>
1744     *
1745     * <p>A <code>null</code> string input will return <code>null</code>.
1746     * An empty ("") string input will return the empty string.
1747     * An empty or <code>null</code> separator will return the input string.</p>
1748     *
1749     * <pre>
1750     * StringUtils.substringBeforeLast(null, *) = null
1751     * StringUtils.substringBeforeLast("", *) = ""
1752     * StringUtils.substringBeforeLast("abcba", "b") = "abc"
1753     * StringUtils.substringBeforeLast("abc", "c") = "ab"
1754     * StringUtils.substringBeforeLast("a", "a") = ""
1755     * StringUtils.substringBeforeLast("a", "z") = "a"
1756     * StringUtils.substringBeforeLast("a", null) = "a"
1757     * StringUtils.substringBeforeLast("a", "") = "a"
1758     * </pre>
1759     *
1760     * @param str the String to get a substring from, may be null
1761     * @param separator the String to search for, may be null
1762     * @return the substring before the last occurrence of the separator,
1763     * <code>null</code> if null String input
1764     * @since 2.0
1765     */

1766    public static String JavaDoc substringBeforeLast(String JavaDoc str, String JavaDoc separator) {
1767        if (isEmpty(str) || isEmpty(separator)) {
1768            return str;
1769        }
1770        int pos = str.lastIndexOf(separator);
1771        if (pos == -1) {
1772            return str;
1773        }
1774        return str.substring(0, pos);
1775    }
1776
1777    /**
1778     * <p>Gets the substring after the last occurrence of a separator.
1779     * The separator is not returned.</p>
1780     *
1781     * <p>A <code>null</code> string input will return <code>null</code>.
1782     * An empty ("") string input will return the empty string.
1783     * An empty or <code>null</code> separator will return the empty string if
1784     * the input string is not <code>null</code>.</p>
1785     *
1786     * <pre>
1787     * StringUtils.substringAfterLast(null, *) = null
1788     * StringUtils.substringAfterLast("", *) = ""
1789     * StringUtils.substringAfterLast(*, "") = ""
1790     * StringUtils.substringAfterLast(*, null) = ""
1791     * StringUtils.substringAfterLast("abc", "a") = "bc"
1792     * StringUtils.substringAfterLast("abcba", "b") = "a"
1793     * StringUtils.substringAfterLast("abc", "c") = ""
1794     * StringUtils.substringAfterLast("a", "a") = ""
1795     * StringUtils.substringAfterLast("a", "z") = ""
1796     * </pre>
1797     *
1798     * @param str the String to get a substring from, may be null
1799     * @param separator the String to search for, may be null
1800     * @return the substring after the last occurrence of the separator,
1801     * <code>null</code> if null String input
1802     * @since 2.0
1803     */

1804    public static String JavaDoc substringAfterLast(String JavaDoc str, String JavaDoc separator) {
1805        if (isEmpty(str)) {
1806            return str;
1807        }
1808        if (isEmpty(separator)) {
1809            return EMPTY;
1810        }
1811        int pos = str.lastIndexOf(separator);
1812        if (pos == -1 || pos == (str.length() - separator.length())) {
1813            return EMPTY;
1814        }
1815        return str.substring(pos + separator.length());
1816    }
1817
1818    // Substring between
1819
//-----------------------------------------------------------------------
1820
/**
1821     * <p>Gets the String that is nested in between two instances of the
1822     * same String.</p>
1823     *
1824     * <p>A <code>null</code> input String returns <code>null</code>.
1825     * A <code>null</code> tag returns <code>null</code>.</p>
1826     *
1827     * <pre>
1828     * StringUtils.substringBetween(null, *) = null
1829     * StringUtils.substringBetween("", "") = ""
1830     * StringUtils.substringBetween("", "tag") = null
1831     * StringUtils.substringBetween("tagabctag", null) = null
1832     * StringUtils.substringBetween("tagabctag", "") = ""
1833     * StringUtils.substringBetween("tagabctag", "tag") = "abc"
1834     * </pre>
1835     *
1836     * @param str the String containing the substring, may be null
1837     * @param tag the String before and after the substring, may be null
1838     * @return the substring, <code>null</code> if no match
1839     * @since 2.0
1840     */

1841    public static String JavaDoc substringBetween(String JavaDoc str, String JavaDoc tag) {
1842        return substringBetween(str, tag, tag);
1843    }
1844
1845    /**
1846     * <p>Gets the String that is nested in between two Strings.
1847     * Only the first match is returned.</p>
1848     *
1849     * <p>A <code>null</code> input String returns <code>null</code>.
1850     * A <code>null</code> open/close returns <code>null</code> (no match).
1851     * An empty ("") open/close returns an empty string.</p>
1852     *
1853     * <pre>
1854     * StringUtils.substringBetween(null, *, *) = null
1855     * StringUtils.substringBetween("", "", "") = ""
1856     * StringUtils.substringBetween("", "", "tag") = null
1857     * StringUtils.substringBetween("", "tag", "tag") = null
1858     * StringUtils.substringBetween("yabcz", null, null) = null
1859     * StringUtils.substringBetween("yabcz", "", "") = ""
1860     * StringUtils.substringBetween("yabcz", "y", "z") = "abc"
1861     * StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc"
1862     * </pre>
1863     *
1864     * @param str the String containing the substring, may be null
1865     * @param open the String before the substring, may be null
1866     * @param close the String after the substring, may be null
1867     * @return the substring, <code>null</code> if no match
1868     * @since 2.0
1869     */

1870    public static String JavaDoc substringBetween(String JavaDoc str, String JavaDoc open, String JavaDoc close) {
1871        if (str == null || open == null || close == null) {
1872            return null;
1873        }
1874        int start = str.indexOf(open);
1875        if (start != -1) {
1876            int end = str.indexOf(close, start + open.length());
1877            if (end != -1) {
1878                return str.substring(start + open.length(), end);
1879            }
1880        }
1881        return null;
1882    }
1883
1884    // Nested extraction
1885
//-----------------------------------------------------------------------
1886
/**
1887     * <p>Gets the String that is nested in between two instances of the
1888     * same String.</p>
1889     *
1890     * <p>A <code>null</code> input String returns <code>null</code>.
1891     * A <code>null</code> tag returns <code>null</code>.</p>
1892     *
1893     * <pre>
1894     * StringUtils.getNestedString(null, *) = null
1895     * StringUtils.getNestedString("", "") = ""
1896     * StringUtils.getNestedString("", "tag") = null
1897     * StringUtils.getNestedString("tagabctag", null) = null
1898     * StringUtils.getNestedString("tagabctag", "") = ""
1899     * StringUtils.getNestedString("tagabctag", "tag") = "abc"
1900     * </pre>
1901     *
1902     * @param str the String containing nested-string, may be null
1903     * @param tag the String before and after nested-string, may be null
1904     * @return the nested String, <code>null</code> if no match
1905     * @deprecated Use the better named {@link #substringBetween(String, String)}.
1906     * Method will be removed in Commons Lang 3.0.
1907     */

1908    public static String JavaDoc getNestedString(String JavaDoc str, String JavaDoc tag) {
1909        return substringBetween(str, tag, tag);
1910    }
1911
1912    /**
1913     * <p>Gets the String that is nested in between two Strings.
1914     * Only the first match is returned.</p>
1915     *
1916     * <p>A <code>null</code> input String returns <code>null</code>.
1917     * A <code>null</code> open/close returns <code>null</code> (no match).
1918     * An empty ("") open/close returns an empty string.</p>
1919     *
1920     * <pre>
1921     * StringUtils.getNestedString(null, *, *) = null
1922     * StringUtils.getNestedString("", "", "") = ""
1923     * StringUtils.getNestedString("", "", "tag") = null
1924     * StringUtils.getNestedString("", "tag", "tag") = null
1925     * StringUtils.getNestedString("yabcz", null, null) = null
1926     * StringUtils.getNestedString("yabcz", "", "") = ""
1927     * StringUtils.getNestedString("yabcz", "y", "z") = "abc"
1928     * StringUtils.getNestedString("yabczyabcz", "y", "z") = "abc"
1929     * </pre>
1930     *
1931     * @param str the String containing nested-string, may be null
1932     * @param open the String before nested-string, may be null
1933     * @param close the String after nested-string, may be null
1934     * @return the nested String, <code>null</code> if no match
1935     * @deprecated Use the better named {@link #substringBetween(String, String, String)}.
1936     * Method will be removed in Commons Lang 3.0.
1937     */

1938    public static String JavaDoc getNestedString(String JavaDoc str, String JavaDoc open, String JavaDoc close) {
1939        return substringBetween(str, open, close);
1940    }
1941
1942    // Splitting
1943
//-----------------------------------------------------------------------
1944
/**
1945     * <p>Splits the provided text into an array, using whitespace as the
1946     * separator.
1947     * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
1948     *
1949     * <p>The separator is not included in the returned String array.
1950     * Adjacent separators are treated as one separator.
1951     * For more control over the split use the StrTokenizer class.</p>
1952     *
1953     * <p>A <code>null</code> input String returns <code>null</code>.</p>
1954     *
1955     * <pre>
1956     * StringUtils.split(null) = null
1957     * StringUtils.split("") = []
1958     * StringUtils.split("abc def") = ["abc", "def"]
1959     * StringUtils.split("abc def") = ["abc", "def"]
1960     * StringUtils.split(" abc ") = ["abc"]
1961     * </pre>
1962     *
1963     * @param str the String to parse, may be null
1964     * @return an array of parsed Strings, <code>null</code> if null String input
1965     */

1966    public static String JavaDoc[] split(String JavaDoc str) {
1967        return split(str, null, -1);
1968    }
1969
1970    /**
1971     * <p>Splits the provided text into an array, separator specified.
1972     * This is an alternative to using StringTokenizer.</p>
1973     *
1974     * <p>The separator is not included in the returned String array.
1975     * Adjacent separators are treated as one separator.
1976     * For more control over the split use the StrTokenizer class.</p>
1977     *
1978     * <p>A <code>null</code> input String returns <code>null</code>.</p>
1979     *
1980     * <pre>
1981     * StringUtils.split(null, *) = null
1982     * StringUtils.split("", *) = []
1983     * StringUtils.split("a.b.c", '.') = ["a", "b", "c"]
1984     * StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
1985     * StringUtils.split("a:b:c", '.') = ["a:b:c"]
1986     * StringUtils.split("a\tb\nc", null) = ["a", "b", "c"]
1987     * StringUtils.split("a b c", ' ') = ["a", "b", "c"]
1988     * </pre>
1989     *
1990     * @param str the String to parse, may be null
1991     * @param separatorChar the character used as the delimiter,
1992     * <code>null</code> splits on whitespace
1993     * @return an array of parsed Strings, <code>null</code> if null String input
1994     * @since 2.0
1995     */

1996    public static String JavaDoc[] split(String JavaDoc str, char separatorChar) {
1997        return splitWorker(str, separatorChar, false);
1998    }
1999
2000    /**
2001     * <p>Splits the provided text into an array, separators specified.
2002     * This is an alternative to using StringTokenizer.</p>
2003     *
2004     * <p>The separator is not included in the returned String array.
2005     * Adjacent separators are treated as one separator.
2006     * For more control over the split use the StrTokenizer class.</p>
2007     *
2008     * <p>A <code>null</code> input String returns <code>null</code>.
2009     * A <code>null</code> separatorChars splits on whitespace.</p>
2010     *
2011     * <pre>
2012     * StringUtils.split(null, *) = null
2013     * StringUtils.split("", *) = []
2014     * StringUtils.split("abc def", null) = ["abc", "def"]
2015     * StringUtils.split("abc def", " ") = ["abc", "def"]
2016     * StringUtils.split("abc def", " ") = ["abc", "def"]
2017     * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
2018     * </pre>
2019     *
2020     * @param str the String to parse, may be null
2021     * @param separatorChars the characters used as the delimiters,
2022     * <code>null</code> splits on whitespace
2023     * @return an array of parsed Strings, <code>null</code> if null String input
2024     */

2025    public static String JavaDoc[] split(String JavaDoc str, String JavaDoc separatorChars) {
2026        return splitWorker(str, separatorChars, -1, false);
2027    }
2028
2029    /**
2030     * <p>Splits the provided text into an array with a maximum length,
2031     * separators specified.</p>
2032     *
2033     * <p>The separator is not included in the returned String array.
2034     * Adjacent separators are treated as one separator.</p>
2035     *
2036     * <p>A <code>null</code> input String returns <code>null</code>.
2037     * A <code>null</code> separatorChars splits on whitespace.</p>
2038     *
2039     * <p>If more than <code>max</code> delimited substrings are found, the last
2040     * returned string includes all characters after the first <code>max - 1</code>
2041     * returned strings (including separator characters).</p>
2042     *
2043     * <pre>
2044     * StringUtils.split(null, *, *) = null
2045     * StringUtils.split("", *, *) = []
2046     * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
2047     * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
2048     * StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
2049     * StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
2050     * </pre>
2051     *
2052     * @param str the String to parse, may be null
2053     * @param separatorChars the characters used as the delimiters,
2054     * <code>null</code> splits on whitespace
2055     * @param max the maximum number of elements to include in the
2056     * array. A zero or negative value implies no limit
2057     * @return an array of parsed Strings, <code>null</code> if null String input
2058     */

2059    public static String JavaDoc[] split(String JavaDoc str, String JavaDoc separatorChars, int max) {
2060        return splitWorker(str, separatorChars, max, false);
2061    }
2062
2063    /**
2064     * <p>Splits the provided text into an array, separator string specified.</p>
2065     *
2066     * <p>The separator(s) will not be included in the returned String array.
2067     * Adjacent separators are treated as one separator.</p>
2068     *
2069     * <p>A <code>null</code> input String returns <code>null</code>.
2070     * A <code>null</code> separator splits on whitespace.</p>
2071     *
2072     * <pre>
2073     * StringUtils.split(null, *) = null
2074     * StringUtils.split("", *) = []
2075     * StringUtils.split("ab de fg", null) = ["ab", "de", "fg"]
2076     * StringUtils.split("ab de fg", null) = ["ab", "de", "fg"]
2077     * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
2078     * StringUtils.split("abstemiouslyaeiouyabstemiously", "aeiouy") = ["bst", "m", "sl", "bst", "m", "sl"]
2079     * StringUtils.split("abstemiouslyaeiouyabstemiously", "aeiouy") = ["abstemiously", "abstemiously"]
2080     * </pre>
2081     *
2082     * @param str the String to parse, may be null
2083     * @param separator String containing the String to be used as a delimiter,
2084     * <code>null</code> splits on whitespace
2085     * @return an array of parsed Strings, <code>null</code> if null String was input
2086     */

2087    public static String JavaDoc[] splitByWholeSeparator(String JavaDoc str, String JavaDoc separator) {
2088        return splitByWholeSeparator( str, separator, -1 ) ;
2089    }
2090
2091    /**
2092     * <p>Splits the provided text into an array, separator string specified.
2093     * Returns a maximum of <code>max</code> substrings.</p>
2094     *
2095     * <p>The separator(s) will not be included in the returned String array.
2096     * Adjacent separators are treated as one separator.</p>
2097     *
2098     * <p>A <code>null</code> input String returns <code>null</code>.
2099     * A <code>null</code> separator splits on whitespace.</p>
2100     *
2101     * <pre>
2102     * StringUtils.splitByWholeSeparator(null, *, *) = null
2103     * StringUtils.splitByWholeSeparator("", *, *) = []
2104     * StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
2105     * StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
2106     * StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2) = ["ab", "cd"]
2107     * StringUtils.splitByWholeSeparator("abstemiouslyaeiouyabstemiously", "aeiouy", 2) = ["bst", "m"]
2108     * StringUtils.splitByWholeSeparator("abstemiouslyaeiouyabstemiously", "aeiouy", 2) = ["abstemiously", "abstemiously"]
2109     * </pre>
2110     *
2111     * @param str the String to parse, may be null
2112     * @param separator String containing the String to be used as a delimiter,
2113     * <code>null</code> splits on whitespace
2114     * @param max the maximum number of elements to include in the returned
2115     * array. A zero or negative value implies no limit.
2116     * @return an array of parsed Strings, <code>null</code> if null String was input
2117     */

2118    public static String JavaDoc[] splitByWholeSeparator( String JavaDoc str, String JavaDoc separator, int max ) {
2119        if (str == null) {
2120            return null;
2121        }
2122
2123        int len = str.length() ;
2124
2125        if (len == 0) {
2126            return ArrayUtils.EMPTY_STRING_ARRAY;
2127        }
2128
2129        if ( ( separator == null ) || ( "".equals( separator ) ) ) {
2130            // Split on whitespace.
2131
return split( str, null, max ) ;
2132        }
2133
2134
2135        int separatorLength = separator.length() ;
2136
2137        ArrayList JavaDoc substrings = new ArrayList JavaDoc() ;
2138        int numberOfSubstrings = 0 ;
2139        int beg = 0 ;
2140        int end = 0 ;
2141        while ( end < len ) {
2142            end = str.indexOf( separator, beg ) ;
2143
2144            if ( end > -1 ) {
2145                if ( end > beg ) {
2146                    numberOfSubstrings += 1 ;
2147
2148                    if ( numberOfSubstrings == max ) {
2149                        end = len ;
2150                        substrings.add( str.substring( beg ) ) ;
2151                    } else {
2152                        // The following is OK, because String.substring( beg, end ) excludes
2153
// the character at the position 'end'.
2154
substrings.add( str.substring( beg, end ) ) ;
2155
2156                        // Set the starting point for the next search.
2157
// The following is equivalent to beg = end + (separatorLength - 1) + 1,
2158
// which is the right calculation:
2159
beg = end + separatorLength ;
2160                    }
2161                } else {
2162                    // We found a consecutive occurrence of the separator, so skip it.
2163
beg = end + separatorLength ;
2164                }
2165            } else {
2166                // String.substring( beg ) goes from 'beg' to the end of the String.
2167
substrings.add( str.substring( beg ) ) ;
2168                end = len ;
2169            }
2170        }
2171
2172        return (String JavaDoc[]) substrings.toArray( new String JavaDoc[substrings.size()] ) ;
2173    }
2174
2175
2176    //-----------------------------------------------------------------------
2177
/**
2178     * <p>Splits the provided text into an array, using whitespace as the
2179     * separator, preserving all tokens, including empty tokens created by
2180     * adjacent separators. This is an alternative to using StringTokenizer.
2181     * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
2182     *
2183     * <p>The separator is not included in the returned String array.
2184     * Adjacent separators are treated as separators for empty tokens.
2185     * For more control over the split use the StrTokenizer class.</p>
2186     *
2187     * <p>A <code>null</code> input String returns <code>null</code>.</p>
2188     *
2189     * <pre>
2190     * StringUtils.splitPreserveAllTokens(null) = null
2191     * StringUtils.splitPreserveAllTokens("") = []
2192     * StringUtils.splitPreserveAllTokens("abc def") = ["abc", "def"]
2193     * StringUtils.splitPreserveAllTokens("abc def") = ["abc", "", "def"]
2194     * StringUtils.splitPreserveAllTokens(" abc ") = ["", "abc", ""]
2195     * </pre>
2196     *
2197     * @param str the String to parse, may be <code>null</code>
2198     * @return an array of parsed Strings, <code>null</code> if null String input
2199     * @since 2.1
2200     */

2201    public static String JavaDoc[] splitPreserveAllTokens(String JavaDoc str) {
2202        return splitWorker(str, null, -1, true);
2203    }
2204
2205    /**
2206     * <p>Splits the provided text into an array, separator specified,
2207     * preserving all tokens, including empty tokens created by adjacent
2208     * separators. This is an alternative to using StringTokenizer.</p>
2209     *
2210     * <p>The separator is not included in the returned String array.
2211     * Adjacent separators are treated as separators for empty tokens.
2212     * For more control over the split use the StrTokenizer class.</p>
2213     *
2214     * <p>A <code>null</code> input String returns <code>null</code>.</p>
2215     *
2216     * <pre>
2217     * StringUtils.splitPreserveAllTokens(null, *) = null
2218     * StringUtils.splitPreserveAllTokens("", *) = []
2219     * StringUtils.splitPreserveAllTokens("a.b.c", '.') = ["a", "b", "c"]
2220     * StringUtils.splitPreserveAllTokens("a..b.c", '.') = ["a", "b", "c"]
2221     * StringUtils.splitPreserveAllTokens("a:b:c", '.') = ["a:b:c"]
2222     * StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
2223     * StringUtils.splitPreserveAllTokens("a b c", ' ') = ["a", "b", "c"]
2224     * StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", ""]
2225     * StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", "", ""]
2226     * StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", a", "b", "c"]
2227     * StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", "", a", "b", "c"]
2228     * StringUtils.splitPreserveAllTokens(" a b c ", ' ') = ["", a", "b", "c", ""]
2229     * </pre>
2230     *
2231     * @param str the String to parse, may be <code>null</code>
2232     * @param separatorChar the character used as the delimiter,
2233     * <code>null</code> splits on whitespace
2234     * @return an array of parsed Strings, <code>null</code> if null String input
2235     * @since 2.1
2236     */

2237    public static String JavaDoc[] splitPreserveAllTokens(String JavaDoc str, char separatorChar) {
2238        return splitWorker(str, separatorChar, true);
2239    }
2240
2241    /**
2242     * Performs the logic for the <code>split</code> and
2243     * <code>splitPreserveAllTokens</code> methods that do not return a
2244     * maximum array length.
2245     *
2246     * @param str the String to parse, may be <code>null</code>
2247     * @param separatorChar the separate character
2248     * @param preserveAllTokens if <code>true</code>, adjacent separators are
2249     * treated as empty token separators; if <code>false</code>, adjacent
2250     * separators are treated as one separator.
2251     * @return an array of parsed Strings, <code>null</code> if null String input
2252     */

2253    private static String JavaDoc[] splitWorker(String JavaDoc str, char separatorChar, boolean preserveAllTokens) {
2254        // Performance tuned for 2.0 (JDK1.4)
2255

2256        if (str == null) {
2257            return null;
2258        }
2259        int len = str.length();
2260        if (len == 0) {
2261            return ArrayUtils.EMPTY_STRING_ARRAY;
2262        }
2263        List JavaDoc list = new ArrayList JavaDoc();
2264        int i = 0, start = 0;
2265        boolean match = false;
2266        boolean lastMatch = false;
2267        while (i < len) {
2268            if (str.charAt(i) == separatorChar) {
2269                if (match || preserveAllTokens) {
2270                    list.add(str.substring(start, i));
2271                    match = false;
2272                    lastMatch = true;
2273                }
2274                start = ++i;
2275                continue;
2276            } else {
2277                lastMatch = false;
2278            }
2279            match = true;
2280            i++;
2281        }
2282        if (match || (preserveAllTokens && lastMatch)) {
2283            list.add(str.substring(start, i));
2284        }
2285        return (String JavaDoc[]) list.toArray(new String JavaDoc[list.size()]);
2286    }
2287
2288    /**
2289     * <p>Splits the provided text into an array, separators specified,
2290     * preserving all tokens, including empty tokens created by adjacent
2291     * separators. This is an alternative to using StringTokenizer.</p>
2292     *
2293     * <p>The separator is not included in the returned String array.
2294     * Adjacent separators are treated as separators for empty tokens.
2295     * For more control over the split use the StrTokenizer class.</p>
2296     *
2297     * <p>A <code>null</code> input String returns <code>null</code>.
2298     * A <code>null</code> separatorChars splits on whitespace.</p>
2299     *
2300     * <pre>
2301     * StringUtils.splitPreserveAllTokens(null, *) = null
2302     * StringUtils.splitPreserveAllTokens("", *) = []
2303     * StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"]
2304     * StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"]
2305     * StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"]
2306     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
2307     * StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""]
2308     * StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
2309     * StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"]
2310     * StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"]
2311     * StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"]
2312     * StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""]
2313     * </pre>
2314     *
2315     * @param str the String to parse, may be <code>null</code>
2316     * @param separatorChars the characters used as the delimiters,
2317     * <code>null</code> splits on whitespace
2318     * @return an array of parsed Strings, <code>null</code> if null String input
2319     * @since 2.1
2320     */

2321    public static String JavaDoc[] splitPreserveAllTokens(String JavaDoc str, String JavaDoc separatorChars) {
2322        return splitWorker(str, separatorChars, -1, true);
2323    }
2324
2325    /**
2326     * <p>Splits the provided text into an array with a maximum length,
2327     * separators specified, preserving all tokens, including empty tokens
2328     * created by adjacent separators.</p>
2329     *
2330     * <p>The separator is not included in the returned String array.
2331     * Adjacent separators are treated as separators for empty tokens.
2332     * Adjacent separators are treated as one separator.</p>
2333     *
2334     * <p>A <code>null</code> input String returns <code>null</code>.
2335     * A <code>null</code> separatorChars splits on whitespace.</p>
2336     *
2337     * <p>If more than <code>max</code> delimited substrings are found, the last
2338     * returned string includes all characters after the first <code>max - 1</code>
2339     * returned strings (including separator characters).</p>
2340     *
2341     * <pre>
2342     * StringUtils.splitPreserveAllTokens(null, *, *) = null
2343     * StringUtils.splitPreserveAllTokens("", *, *) = []
2344     * StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"]
2345     * StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"]
2346     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
2347     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
2348     * StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"]
2349     * StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"]
2350     * StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"]
2351     * </pre>
2352     *
2353     * @param str the String to parse, may be <code>null</code>
2354     * @param separatorChars the characters used as the delimiters,
2355     * <code>null</code> splits on whitespace
2356     * @param max the maximum number of elements to include in the
2357     * array. A zero or negative value implies no limit
2358     * @return an array of parsed Strings, <code>null</code> if null String input
2359     * @since 2.1
2360     */

2361    public static String JavaDoc[] splitPreserveAllTokens(String JavaDoc str, String JavaDoc separatorChars, int max) {
2362        return splitWorker(str, separatorChars, max, true);
2363    }
2364
2365    /**
2366     * Performs the logic for the <code>split</code> and
2367     * <code>splitPreserveAllTokens</code> methods that return a maximum array
2368     * length.
2369     *
2370     * @param str the String to parse, may be <code>null</code>
2371     * @param separatorChars the separate character
2372     * @param max the maximum number of elements to include in the
2373     * array. A zero or negative value implies no limit.
2374     * @param preserveAllTokens if <code>true</code>, adjacent separators are
2375     * treated as empty token separators; if <code>false</code>, adjacent
2376     * separators are treated as one separator.
2377     * @return an array of parsed Strings, <code>null</code> if null String input
2378     */

2379    private static String JavaDoc[] splitWorker(String JavaDoc str, String JavaDoc separatorChars, int max, boolean preserveAllTokens) {
2380        // Performance tuned for 2.0 (JDK1.4)
2381
// Direct code is quicker than StringTokenizer.
2382
// Also, StringTokenizer uses isSpace() not isWhitespace()
2383

2384        if (str == null) {
2385            return null;
2386        }
2387        int len = str.length();
2388        if (len == 0) {
2389            return ArrayUtils.EMPTY_STRING_ARRAY;
2390        }
2391        List JavaDoc list = new ArrayList JavaDoc();
2392        int sizePlus1 = 1;
2393        int i = 0, start = 0;
2394        boolean match = false;
2395        boolean lastMatch = false;
2396        if (separatorChars == null) {
2397            // Null separator means use whitespace
2398
while (i < len) {
2399                if (Character.isWhitespace(str.charAt(i))) {
2400                    if (match || preserveAllTokens) {
2401                        lastMatch = true;
2402                        if (sizePlus1++ == max) {
2403                            i = len;
2404                            lastMatch = false;
2405                        }
2406                        list.add(str.substring(start, i));
2407                        match = false;
2408                    }
2409                    start = ++i;
2410                    continue;
2411                } else {
2412                    lastMatch = false;
2413                }
2414                match = true;
2415                i++;
2416            }
2417        } else if (separatorChars.length() == 1) {
2418            // Optimise 1 character case
2419
char sep = separatorChars.charAt(0);
2420            while (i < len) {
2421                if (str.charAt(i) == sep) {
2422                    if (match || preserveAllTokens) {
2423                        lastMatch = true;
2424                        if (sizePlus1++ == max) {
2425                            i = len;
2426                            lastMatch = false;
2427                        }
2428                        list.add(str.substring(start, i));
2429                        match = false;
2430                    }
2431                    start = ++i;
2432                    continue;
2433                } else {
2434                    lastMatch = false;
2435                }
2436                match = true;
2437                i++;
2438            }
2439        } else {
2440            // standard case
2441
while (i < len) {
2442                if (separatorChars.indexOf(str.charAt(i)) >= 0) {
2443                    if (match || preserveAllTokens) {
2444                        lastMatch = true;
2445                        if (sizePlus1++ == max) {
2446                            i = len;
2447                            lastMatch = false;
2448                        }
2449                        list.add(str.substring(start, i));
2450                        match = false;
2451                    }
2452                    start = ++i;
2453                    continue;
2454                } else {
2455                    lastMatch = false;
2456                }
2457                match = true;
2458                i++;
2459            }
2460        }
2461        if (match || (preserveAllTokens && lastMatch)) {
2462            list.add(str.substring(start, i));
2463        }
2464        return (String JavaDoc[]) list.toArray(new String JavaDoc[list.size()]);
2465    }
2466
2467    // Joining
2468
//-----------------------------------------------------------------------
2469
/**
2470     * <p>Concatenates elements of an array into a single String.
2471     * Null objects or empty strings within the array are represented by
2472     * empty strings.</p>
2473     *
2474     * <pre>
2475     * StringUtils.concatenate(null) = null
2476     * StringUtils.concatenate([]) = ""
2477     * StringUtils.concatenate([null]) = ""
2478     * StringUtils.concatenate(["a", "b", "c"]) = "abc"
2479     * StringUtils.concatenate([null, "", "a"]) = "a"
2480     * </pre>
2481     *
2482     * @param array the array of values to concatenate, may be null
2483     * @return the concatenated String, <code>null</code> if null array input
2484     * @deprecated Use the better named {@link #join(Object[])} instead.
2485     * Method will be removed in Commons Lang 3.0.
2486     */

2487    public static String JavaDoc concatenate(Object JavaDoc[] array) {
2488        return join(array, null);
2489    }
2490
2491    /**
2492     * <p>Joins the elements of the provided array into a single String
2493     * containing the provided list of elements.</p>
2494     *
2495     * <p>No separator is added to the joined String.
2496     * Null objects or empty strings within the array are represented by
2497     * empty strings.</p>
2498     *
2499     * <pre>
2500     * StringUtils.join(null) = null
2501     * StringUtils.join([]) = ""
2502     * StringUtils.join([null]) = ""
2503     * StringUtils.join(["a", "b", "c"]) = "abc"
2504     * StringUtils.join([null, "", "a"]) = "a"
2505     * </pre>
2506     *
2507     * @param array the array of values to join together, may be null
2508     * @return the joined String, <code>null</code> if null array input
2509     * @since 2.0
2510     */

2511    public static String JavaDoc join(Object JavaDoc[] array) {
2512        return join(array, null);
2513    }
2514
2515    /**
2516     * <p>Joins the elements of the provided array into a single String
2517     * containing the provided list of elements.</p>
2518     *
2519     * <p>No delimiter is added before or after the list.
2520     * Null objects or empty strings within the array are represented by
2521     * empty strings.</p>
2522     *
2523     * <pre>
2524     * StringUtils.join(null, *) = null
2525     * StringUtils.join([], *) = ""
2526     * StringUtils.join([null], *) = ""
2527     * StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
2528     * StringUtils.join(["a", "b", "c"], null) = "abc"
2529     * StringUtils.join([null, "", "a"], ';') = ";;a"
2530     * </pre>
2531     *
2532     * @param array the array of values to join together, may be null
2533     * @param separator the separator character to use
2534     * @return the joined String, <code>null</code> if null array input
2535     * @since 2.0
2536     */

2537    public static String JavaDoc join(Object JavaDoc[] array, char separator) {
2538        if (array == null) {
2539            return null;
2540        }
2541        int arraySize = array.length;
2542        int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].toString().length()) + 1) * arraySize);
2543        StringBuffer JavaDoc buf = new StringBuffer JavaDoc(bufSize);
2544
2545        for (int i = 0; i < arraySize; i++) {
2546            if (i > 0) {
2547                buf.append(separator);
2548            }
2549            if (array[i] != null) {
2550                buf.append(array[i]);
2551            }
2552        }
2553        return buf.toString();
2554    }
2555
2556    /**
2557     * <p>Joins the elements of the provided array into a single String
2558     * containing the provided list of elements.</p>
2559     *
2560     * <p>No delimiter is added before or after the list.
2561     * A <code>null</code> separator is the same as an empty String ("").
2562     * Null objects or empty strings within the array are represented by
2563     * empty strings.</p>
2564     *
2565     * <pre>
2566     * StringUtils.join(null, *) = null
2567     * StringUtils.join([], *) = ""
2568     * StringUtils.join([null], *) = ""
2569     * StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
2570     * StringUtils.join(["a", "b", "c"], null) = "abc"
2571     * StringUtils.join(["a", "b", "c"], "") = "abc"
2572     * StringUtils.join([null, "", "a"], ',') = ",,a"
2573     * </pre>
2574     *
2575     * @param array the array of values to join together, may be null
2576     * @param separator the separator character to use, null treated as ""
2577     * @return the joined String, <code>null</code> if null array input
2578     */

2579    public static String JavaDoc join(Object JavaDoc[] array, String JavaDoc separator) {
2580        if (array == null) {
2581            return null;
2582        }
2583        if (separator == null) {
2584            separator = EMPTY;
2585        }
2586        int arraySize = array.length;
2587
2588        // ArraySize == 0: Len = 0
2589
// ArraySize > 0: Len = NofStrings *(len(firstString) + len(separator))
2590
// (Assuming that all Strings are roughly equally long)
2591
int bufSize =
2592            ((arraySize == 0)
2593                ? 0
2594                : arraySize
2595                    * ((array[0] == null ? 16 : array[0].toString().length())
2596                        + separator.length()));
2597
2598        StringBuffer JavaDoc buf = new StringBuffer JavaDoc(bufSize);
2599
2600        for (int i = 0; i < arraySize; i++) {
2601            if (i > 0) {
2602                buf.append(separator);
2603            }
2604            if (array[i] != null) {
2605                buf.append(array[i]);
2606            }
2607        }
2608        return buf.toString();
2609    }
2610
2611    /**
2612     * <p>Joins the elements of the provided <code>Iterator</code> into
2613     * a single String containing the provided elements.</p>
2614     *
2615     * <p>No delimiter is added before or after the list. Null objects or empty
2616     * strings within the iteration are represented by empty strings.</p>
2617     *
2618     * <p>See the examples here: {@link #join(Object[],char)}. </p>
2619     *
2620     * @param iterator the <code>Iterator</code> of values to join together, may be null
2621     * @param separator the separator character to use
2622     * @return the joined String, <code>null</code> if null iterator input
2623     * @since 2.0
2624     */

2625    public static String JavaDoc join(Iterator JavaDoc iterator, char separator) {
2626        if (iterator == null) {
2627            return null;
2628        }
2629        StringBuffer JavaDoc buf = new StringBuffer JavaDoc(256); // Java default is 16, probably too small
2630
while (iterator.hasNext()) {
2631            Object JavaDoc obj = iterator.next();
2632            if (obj != null) {
2633                buf.append(obj);
2634            }
2635            if (iterator.hasNext()) {
2636                buf.append(separator);
2637            }
2638        }
2639        return buf.toString();
2640    }
2641
2642    /**
2643     * <p>Joins the elements of the provided <code>Iterator</code> into
2644     * a single String containing the provided elements.</p>
2645     *
2646     * <p>No delimiter is added before or after the list.
2647     * A <code>null</code> separator is the same as an empty String ("").</p>
2648     *
2649     * <p>See the examples here: {@link #join(Object[],String)}. </p>
2650     *
2651     * @param iterator the <code>Iterator</code> of values to join together, may be null
2652     * @param separator the separator character to use, null treated as ""
2653     * @return the joined String, <code>null</code> if null iterator input
2654     */

2655    public static String JavaDoc join(Iterator JavaDoc iterator, String JavaDoc separator) {
2656        if (iterator == null) {
2657            return null;
2658        }
2659        StringBuffer JavaDoc buf = new StringBuffer JavaDoc(256); // Java default is 16, probably too small
2660
while (iterator.hasNext()) {
2661            Object JavaDoc obj = iterator.next();
2662            if (obj != null) {
2663                buf.append(obj);
2664            }
2665            if ((separator != null) && iterator.hasNext()) {
2666                buf.append(separator);
2667            }
2668        }
2669        return buf.toString();
2670    }
2671
2672    // Delete
2673
//-----------------------------------------------------------------------
2674
/**
2675     * <p>Deletes all 'space' characters from a String as defined by
2676     * {@link Character#isSpace(char)}.</p>
2677     *
2678     * <p>This is the only StringUtils method that uses the
2679     * <code>isSpace</code> definition. You are advised to use
2680     * {@link #deleteWhitespace(String)} instead as whitespace is much
2681     * better localized.</p>
2682     *
2683     * <pre>
2684     * StringUtils.deleteSpaces(null) = null
2685     * StringUtils.deleteSpaces("") = ""
2686     * StringUtils.deleteSpaces("abc") = "abc"
2687     * StringUtils.deleteSpaces(" \t abc \n ") = "abc"
2688     * StringUtils.deleteSpaces("ab c") = "abc"
2689     * StringUtils.deleteSpaces("a\nb\tc ") = "abc"
2690     * </pre>
2691     *
2692     * <p>Spaces are defined as <code>{' ', '\t', '\r', '\n', '\b'}</code>
2693     * in line with the deprecated <code>isSpace</code> method.</p>
2694     *
2695     * @param str the String to delete spaces from, may be null
2696     * @return the String without 'spaces', <code>null</code> if null String input
2697     * @deprecated Use the better localized {@link #deleteWhitespace(String)}.
2698     * Method will be removed in Commons Lang 3.0.
2699     */

2700    public static String JavaDoc deleteSpaces(String JavaDoc str) {
2701        if (str == null) {
2702            return null;
2703        }
2704        return CharSetUtils.delete(str, " \t\r\n\b");
2705    }
2706
2707    /**
2708     * <p>Deletes all whitespaces from a String as defined by
2709     * {@link Character#isWhitespace(char)}.</p>
2710     *
2711     * <pre>
2712     * StringUtils.deleteWhitespace(null) = null
2713     * StringUtils.deleteWhitespace("") = ""
2714     * StringUtils.deleteWhitespace("abc") = "abc"
2715     * StringUtils.deleteWhitespace(" ab c ") = "abc"
2716     * </pre>
2717     *
2718     * @param str the String to delete whitespace from, may be null
2719     * @return the String without whitespaces, <code>null</code> if null String input
2720     */

2721    public static String JavaDoc deleteWhitespace(String JavaDoc str) {
2722        if (isEmpty(str)) {
2723            return str;
2724        }
2725        int sz = str.length();
2726        char[] chs = new char[sz];
2727        int count = 0;
2728        for (int i = 0; i < sz; i++) {
2729            if (!Character.isWhitespace(str.charAt(i))) {
2730                chs[count++] = str.charAt(i);
2731            }
2732        }
2733        if (count == sz) {
2734            return str;
2735        }
2736        return new String JavaDoc(chs, 0, count);
2737    }
2738
2739    // Remove
2740
//-----------------------------------------------------------------------
2741
/**
2742     * <p>Removes a substring only if it is at the begining of a source string,
2743     * otherwise returns the source string.</p>
2744     *
2745     * <p>A <code>null</code> source string will return <code>null</code>.
2746     * An empty ("") source string will return the empty string.
2747     * A <code>null</code> search string will return the source string.</p>
2748     *
2749     * <pre>
2750     * StringUtils.removeStart(null, *) = null
2751     * StringUtils.removeStart("", *) = ""
2752     * StringUtils.removeStart(*, null) = *
2753     * StringUtils.removeStart("www.domain.com", "www.") = "domain.com"
2754     * StringUtils.removeStart("domain.com", "www.") = "domain.com"
2755     * StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
2756     * StringUtils.removeStart("abc", "") = "abc"
2757     * </pre>
2758     *
2759     * @param str the source String to search, may be null
2760     * @param remove the String to search for and remove, may be null
2761     * @return the substring with the string removed if found,
2762     * <code>null</code> if null String input
2763     * @since 2.1
2764     */

2765    public static String JavaDoc removeStart(String JavaDoc str, String JavaDoc remove) {
2766        if (isEmpty(str) || isEmpty(remove)) {
2767            return str;
2768        }
2769        if (str.startsWith(remove)){
2770            return str.substring(remove.length());
2771        }
2772        return str;
2773    }
2774
2775    /**
2776     * <p>Removes a substring only if it is at the end of a source string,
2777     * otherwise returns the source string.</p>
2778     *
2779     * <p>A <code>null</code> source string will return <code>null</code>.
2780     * An empty ("") source string will return the empty string.
2781     * A <code>null</code> search string will return the source string.</p>
2782     *
2783     * <pre>
2784     * StringUtils.removeEnd(null, *) = null
2785     * StringUtils.removeEnd("", *) = ""
2786     * StringUtils.removeEnd(*, null) = *
2787     * StringUtils.removeEnd("www.domain.com", ".com.") = "www,domain"
2788     * StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
2789     * StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
2790     * StringUtils.removeEnd("abc", "") = "abc"
2791     * </pre>
2792     *
2793     * @param str the source String to search, may be null
2794     * @param remove the String to search for and remove, may be null
2795     * @return the substring with the string removed if found,
2796     * <code>null</code> if null String input
2797     * @since 2.1
2798     */

2799    public static String JavaDoc removeEnd(String JavaDoc str, String JavaDoc remove) {
2800        if (isEmpty(str) || isEmpty(remove)) {
2801            return str;
2802        }
2803        if (str.endsWith(remove)) {
2804            return str.substring(0, str.length() - remove.length());
2805        }
2806        return str;
2807    }
2808
2809    /**
2810     * <p>Removes all occurances of a substring from within the source string.</p>
2811     *
2812     * <p>A <code>null</code> source string will return <code>null</code>.
2813     * An empty ("") source string will return the empty string.
2814     * A <code>null</code> remove string will return the source string.
2815     * An empty ("") remove string will return the source string.</p>
2816     *
2817     * <pre>
2818     * StringUtils.remove(null, *) = null
2819     * StringUtils.remove("", *) = ""
2820     * StringUtils.remove(*, null) = *
2821     * StringUtils.remove(*, "") = *
2822     * StringUtils.remove("queued", "ue") = "qd"
2823     * StringUtils.remove("queued", "zz") = "queued"
2824     * </pre>
2825     *
2826     * @param str the source String to search, may be null
2827     * @param remove the String to search for and remove, may be null
2828     * @return the substring with the string removed if found,
2829     * <code>null</code> if null String input
2830     * @since 2.1
2831     */

2832    public static String JavaDoc remove(String JavaDoc str, String JavaDoc remove) {
2833        if (isEmpty(str) || isEmpty(remove)) {
2834            return str;
2835        }
2836        return replace(str, remove, "", -1);
2837    }
2838
2839    /**
2840     * <p>Removes all occurances of a character from within the source string.</p>
2841     *
2842     * <p>A <code>null</code> source string will return <code>null</code>.
2843     * An empty ("") source string will return the empty string.</p>
2844     *
2845     * <pre>
2846     * StringUtils.remove(null, *) = null
2847     * StringUtils.remove("", *) = ""
2848     * StringUtils.remove("queued", 'u') = "qeed"
2849     * StringUtils.remove("queued", 'z') = "queued"
2850     * </pre>
2851     *
2852     * @param str the source String to search, may be null
2853     * @param remove the char to search for and remove, may be null
2854     * @return the substring with the char removed if found,
2855     * <code>null</code> if null String input
2856     * @since 2.1
2857     */

2858    public static String JavaDoc remove(String JavaDoc str, char remove) {
2859        if (isEmpty(str) || str.indexOf(remove) == -1) {
2860            return str;
2861        }
2862        char[] chars = str.toCharArray();
2863        int pos = 0;
2864        for (int i = 0; i < chars.length; i++) {
2865            if (chars[i] != remove) {
2866                chars[pos++] = chars[i];
2867            }
2868        }
2869        return new String JavaDoc(chars, 0, pos);
2870    }
2871
2872    // Replacing
2873
//-----------------------------------------------------------------------
2874
/**
2875     * <p>Replaces a String with another String inside a larger String, once.</p>
2876     *
2877     * <p>A <code>null</code> reference passed to this method is a no-op.</p>
2878     *
2879     * <pre>
2880     * StringUtils.replaceOnce(null, *, *) = null
2881     * StringUtils.replaceOnce("", *, *) = ""
2882     * StringUtils.replaceOnce("any", null, *) = "any"
2883     * StringUtils.replaceOnce("any", *, null) = "any"
2884     * StringUtils.replaceOnce("any", "", *) = "any"
2885     * StringUtils.replaceOnce("aba", "a", null) = "aba"
2886     * StringUtils.replaceOnce("aba", "a", "") = "ba"
2887     * StringUtils.replaceOnce("aba", "a", "z") = "zba"
2888     * </pre>
2889     *
2890     * @see #replace(String text, String repl, String with, int max)
2891     * @param text text to search and replace in, may be null
2892     * @param repl the String to search for, may be null
2893     * @param with the String to replace with, may be null
2894     * @return the text with any replacements processed,
2895     * <code>null</code> if null String input
2896     */

2897    public static String JavaDoc replaceOnce(String JavaDoc text, String JavaDoc repl, String JavaDoc with) {
2898        return replace(text, repl, with, 1);
2899    }
2900
2901    /**
2902     * <p>Replaces all occurrences of a String within another String.</p>
2903     *
2904     * <p>A <code>null</code> reference passed to this method is a no-op.</p>
2905     *
2906     * <pre>
2907     * StringUtils.replace(null, *, *) = null
2908     * StringUtils.replace("", *, *) = ""
2909     * StringUtils.replace("any", null, *) = "any"
2910     * StringUtils.replace("any", *, null) = "any"
2911     * StringUtils.replace("any", "", *) = "any"
2912     * StringUtils.replace("aba", "a", null) = "aba"
2913     * StringUtils.replace("aba", "a", "") = "b"
2914     * StringUtils.replace("aba", "a", "z") = "zbz"
2915     * </pre>
2916     *
2917     * @see #replace(String text, String repl, String with, int max)
2918     * @param text text to search and replace in, may be null
2919     * @param repl the String to search for, may be null
2920     * @param with the String to replace with, may be null
2921     * @return the text with any replacements processed,
2922     * <code>null</code> if null String input
2923     */

2924    public static String JavaDoc replace(String JavaDoc text, String JavaDoc repl, String JavaDoc with) {
2925        return replace(text, repl, with, -1);
2926    }
2927
2928    /**
2929     * <p>Replaces a String with another String inside a larger String,
2930     * for the first <code>max</code> values of the search String.</p>
2931     *
2932     * <p>A <code>null</code> reference passed to this method is a no-op.</p>
2933     *
2934     * <pre>
2935     * StringUtils.replace(null, *, *, *) = null
2936     * StringUtils.replace("", *, *, *) = ""
2937     * StringUtils.replace("any", null, *, *) = "any"
2938     * StringUtils.replace("any", *, null, *) = "any"
2939     * StringUtils.replace("any", "", *, *) = "any"
2940     * StringUtils.replace("any", *, *, 0) = "any"
2941     * StringUtils.replace("abaa", "a", null, -1) = "abaa"
2942     * StringUtils.replace("abaa", "a", "", -1) = "b"
2943     * StringUtils.replace("abaa", "a", "z", 0) = "abaa"
2944     * StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
2945     * StringUtils.replace("abaa", "a", "z", 2) = "zbza"
2946     * StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
2947     * </pre>
2948     *
2949     * @param text text to search and replace in, may be null
2950     * @param repl the String to search for, may be null
2951     * @param with the String to replace with, may be null
2952     * @param max maximum number of values to replace, or <code>-1</code> if no maximum
2953     * @return the text with any replacements processed,
2954     * <code>null</code> if null String input
2955     */

2956    public static String JavaDoc replace(String JavaDoc text, String JavaDoc repl, String JavaDoc with, int max) {
2957        if (text == null || isEmpty(repl) || with == null || max == 0) {
2958            return text;
2959        }
2960
2961        StringBuffer JavaDoc buf = new StringBuffer JavaDoc(text.length());
2962        int start = 0, end = 0;
2963        while ((end = text.indexOf(repl, start)) != -1) {
2964            buf.append(text.substring(start, end)).append(with);
2965            start = end + repl.length();
2966
2967            if (--max == 0) {
2968                break;
2969            }
2970        }
2971        buf.append(text.substring(start));
2972        return buf.toString();
2973    }
2974
2975    // Replace, character based
2976
//-----------------------------------------------------------------------
2977
/**
2978     * <p>Replaces all occurrences of a character in a String with another.
2979     * This is a null-safe version of {@link String#replace(char, char)}.</p>
2980     *
2981     * <p>A <code>null</code> string input returns <code>null</code>.
2982     * An empty ("") string input returns an empty string.</p>
2983     *
2984     * <pre>
2985     * StringUtils.replaceChars(null, *, *) = null
2986     * StringUtils.replaceChars("", *, *) = ""
2987     * StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
2988     * StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
2989     * </pre>
2990     *
2991     * @param str String to replace characters in, may be null
2992     * @param searchChar the character to search for, may be null
2993     * @param replaceChar the character to replace, may be null
2994     * @return modified String, <code>null</code> if null string input
2995     * @since 2.0
2996     */

2997    public static String JavaDoc replaceChars(String JavaDoc str, char searchChar, char replaceChar) {
2998        if (str == null) {
2999            return null;
3000        }
3001        return str.replace(searchChar, replaceChar);
3002    }
3003
3004    /**
3005     * <p>Replaces multiple characters in a String in one go.
3006     * This method can also be used to delete characters.</p>
3007     *
3008     * <p>For example:<br />
3009     * <code>replaceChars(&quot;hello&quot;, &quot;ho&quot;, &quot;jy&quot;) = jelly</code>.</p>
3010     *
3011     * <p>A <code>null</code> string input returns <code>null</code>.
3012     * An empty ("") string input returns an empty string.
3013     * A null or empty set of search characters returns the input string.</p>
3014     *
3015     * <p>The length of the search characters should normally equal the length
3016     * of the replace characters.
3017     * If the search characters is longer, then the extra search characters
3018     * are deleted.
3019     * If the search characters is shorter, then the extra replace characters
3020     * are ignored.</p>
3021     *
3022     * <pre>
3023     * StringUtils.replaceChars(null, *, *) = null
3024     * StringUtils.replaceChars("", *, *) = ""
3025     * StringUtils.replaceChars("abc", null, *) = "abc"
3026     * StringUtils.replaceChars("abc", "", *) = "abc"
3027     * StringUtils.replaceChars("abc", "b", null) = "ac"
3028     * StringUtils.replaceChars("abc", "b", "") = "ac"
3029     * StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya"
3030     * StringUtils.replaceChars("abcba", "bc", "y") = "ayya"
3031     * StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
3032     * </pre>
3033     *
3034     * @param str String to replace characters in, may be null
3035     * @param searchChars a set of characters to search for, may be null
3036     * @param replaceChars a set of characters to replace, may be null
3037     * @return modified String, <code>null</code> if null string input
3038     * @since 2.0
3039     */

3040    public static String JavaDoc replaceChars(String JavaDoc str, String JavaDoc searchChars, String JavaDoc replaceChars) {
3041        if (isEmpty(str) || isEmpty(searchChars)) {
3042            return str;
3043        }
3044        if (replaceChars == null) {
3045            replaceChars = "";
3046        }
3047        boolean modified = false;
3048        StringBuffer JavaDoc buf = new StringBuffer JavaDoc(str.length());
3049        for (int i = 0; i < str.length(); i++) {
3050            char ch = str.charAt(i);
3051            int index = searchChars.indexOf(ch);
3052            if (index >= 0) {
3053                modified = true;
3054                if (index < replaceChars.length()) {
3055                    buf.append(replaceChars.charAt(index));
3056                }
3057            } else {
3058                buf.append(ch);
3059            }
3060        }
3061        if (modified) {
3062            return buf.toString();
3063        } else {
3064            return str;
3065        }
3066    }
3067
3068    // Overlay
3069
//-----------------------------------------------------------------------
3070
/**
3071     * <p>Overlays part of a String with another String.</p>
3072     *
3073     * <pre>
3074     * StringUtils.overlayString(null, *, *, *) = NullPointerException
3075     * StringUtils.overlayString(*, null, *, *) = NullPointerException
3076     * StringUtils.overlayString("", "abc", 0, 0) = "abc"
3077     * StringUtils.overlayString("abcdef", null, 2, 4) = "abef"
3078     * StringUtils.overlayString("abcdef", "", 2, 4) = "abef"
3079     * StringUtils.overlayString("abcdef", "zzzz", 2, 4) = "abzzzzef"
3080     * StringUtils.overlayString("abcdef", "zzzz", 4, 2) = "abcdzzzzcdef"
3081     * StringUtils.overlayString("abcdef", "zzzz", -1, 4) = IndexOutOfBoundsException
3082     * StringUtils.overlayString("abcdef", "zzzz", 2, 8) = IndexOutOfBoundsException
3083     * </pre>
3084     *
3085     * @param text the String to do overlaying in, may be null
3086     * @param overlay the String to overlay, may be null
3087     * @param start the position to start overlaying at, must be valid
3088     * @param end the position to stop overlaying before, must be valid
3089     * @return overlayed String, <code>null</code> if null String input
3090     * @throws NullPointerException if text or overlay is null
3091     * @throws IndexOutOfBoundsException if either position is invalid
3092     * @deprecated Use better named {@link #overlay(String, String, int, int)} instead.
3093     * Method will be removed in Commons Lang 3.0.
3094     */

3095    public static String JavaDoc overlayString(String JavaDoc text, String JavaDoc overlay, int start, int end) {
3096        return new StringBuffer JavaDoc(start + overlay.length() + text.length() - end + 1)
3097            .append(text.substring(0, start))
3098            .append(overlay)
3099            .append(text.substring(end))
3100            .toString();
3101    }
3102
3103    /**
3104     * <p>Overlays part of a String with another String.</p>
3105     *
3106     * <p>A <code>null</code> string input returns <code>null</code>.
3107     * A negative index is treated as zero.
3108     * An index greater than the string length is treated as the string length.
3109     * The start index is always the smaller of the two indices.</p>
3110     *
3111     * <pre>
3112     * StringUtils.overlay(null, *, *, *) = null
3113     * StringUtils.overlay("", "abc", 0, 0) = "abc"
3114     * StringUtils.overlay("abcdef", null, 2, 4) = "abef"
3115     * StringUtils.overlay("abcdef", "", 2, 4) = "abef"
3116     * StringUtils.overlay("abcdef", "", 4, 2) = "abef"
3117     * StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef"
3118     * StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef"
3119     * StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef"
3120     * StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz"
3121     * StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
3122     * StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
3123     * </pre>
3124     *
3125     * @param str the String to do overlaying in, may be null
3126     * @param overlay the String to overlay, may be null
3127     * @param start the position to start overlaying at
3128     * @param end the position to stop overlaying before
3129     * @return overlayed String, <code>null</code> if null String input
3130     * @since 2.0
3131     */

3132    public static String JavaDoc overlay(String JavaDoc str, String JavaDoc overlay, int start, int end) {
3133        if (str == null) {
3134            return null;
3135        }
3136        if (overlay == null) {
3137            overlay = EMPTY;
3138        }
3139        int len = str.length();
3140        if (start < 0) {
3141            start = 0;
3142        }
3143        if (start > len) {
3144            start = len;
3145        }
3146        if (end < 0) {
3147            end = 0;
3148        }
3149        if (end > len) {
3150            end = len;
3151        }
3152        if (start > end) {
3153            int temp = start;
3154            start = end;
3155            end = temp;
3156        }
3157        return new StringBuffer JavaDoc(len + start - end + overlay.length() + 1)
3158            .append(str.substring(0, start))
3159            .append(overlay)
3160            .append(str.substring(end))
3161            .toString();
3162    }
3163
3164    // Chomping
3165
//-----------------------------------------------------------------------
3166
/**
3167     * <p>Removes one newline from end of a String if it's there,
3168     * otherwise leave it alone. A newline is &quot;<code>\n</code>&quot;,
3169     * &quot;<code>\r</code>&quot;, or &quot;<code>\r\n</code>&quot;.</p>
3170     *
3171     * <p>NOTE: This method changed in 2.0.
3172     * It now more closely matches Perl chomp.</p>
3173     *
3174     * <pre>
3175     * StringUtils.chomp(null) = null
3176     * StringUtils.chomp("") = ""
3177     * StringUtils.chomp("abc \r") = "abc "
3178     * StringUtils.chomp("abc\n") = "abc"
3179     * StringUtils.chomp("abc\r\n") = "abc"
3180     * StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
3181     * StringUtils.chomp("abc\n\r") = "abc\n"
3182     * StringUtils.chomp("abc\n\rabc") = "abc\n\rabc"
3183     * StringUtils.chomp("\r") = ""
3184     * StringUtils.chomp("\n") = ""
3185     * StringUtils.chomp("\r\n") = ""
3186     * </pre>
3187     *
3188     * @param str the String to chomp a newline from, may be null
3189     * @return String without newline, <code>null</code> if null String input
3190     */

3191    public static String JavaDoc chomp(String JavaDoc str) {
3192        if (isEmpty(str)) {
3193            return str;
3194        }
3195
3196        if (str.length() == 1) {
3197            char ch = str.charAt(0);
3198            if (ch == '\r' || ch == '\n') {
3199                return EMPTY;
3200            } else {
3201                return str;
3202            }
3203        }
3204
3205        int lastIdx = str.length() - 1;
3206        char last = str.charAt(lastIdx);
3207
3208        if (last == '\n') {
3209            if (str.charAt(lastIdx - 1) == '\r') {
3210                lastIdx--;
3211            }
3212        } else if (last == '\r') {
3213            // why is this block empty?
3214
// just to skip incrementing the index?
3215
} else {
3216            lastIdx++;
3217        }
3218        return str.substring(0, lastIdx);
3219    }
3220
3221    /**
3222     * <p>Removes <code>separator</code> from the end of
3223     * <code>str</code> if it's there, otherwise leave it alone.</p>
3224     *
3225     * <p>NOTE: This method changed in version 2.0.
3226     * It now more closely matches Perl chomp.
3227     * For the previous behavior, use {@link #substringBeforeLast(String, String)}.
3228     * This method uses {@link String#endsWith(String)}.</p>
3229     *
3230     * <pre>
3231     * StringUtils.chomp(null, *) = null
3232     * StringUtils.chomp("", *) = ""
3233     * StringUtils.chomp("foobar", "bar") = "foo"
3234     * StringUtils.chomp("foobar", "baz") = "foobar"
3235     * StringUtils.chomp("foo", "foo") = ""
3236     * StringUtils.chomp("foo ", "foo") = "foo "
3237     * StringUtils.chomp(" foo", "foo") = " "
3238     * StringUtils.chomp("foo", "foooo") = "foo"
3239     * StringUtils.chomp("foo", "") = "foo"
3240     * StringUtils.chomp("foo", null) = "foo"
3241     * </pre>
3242     *
3243     * @param str the String to chomp from, may be null
3244     * @param separator separator String, may be null
3245     * @return String without trailing separator, <code>null</code> if null String input
3246     */

3247    public static String JavaDoc chomp(String JavaDoc str, String JavaDoc separator) {
3248        if (isEmpty(str) || separator == null) {
3249            return str;
3250        }
3251        if (str.endsWith(separator)) {
3252            return str.substring(0, str.length() - separator.length());
3253        }
3254        return str;
3255    }
3256
3257    /**
3258     * <p>Remove any &quot;\n&quot; if and only if it is at the end
3259     * of the supplied String.</p>
3260     *
3261     * @param str the String to chomp from, must not be null
3262     * @return String without chomped ending
3263     * @throws NullPointerException if str is <code>null</code>
3264     * @deprecated Use {@link #chomp(String)} instead.
3265     * Method will be removed in Commons Lang 3.0.
3266     */

3267    public static String JavaDoc chompLast(String JavaDoc str) {
3268        return chompLast(str, "\n");
3269    }
3270
3271    /**
3272     * <p>Remove a value if and only if the String ends with that value.</p>
3273     *
3274     * @param str the String to chomp from, must not be null
3275     * @param sep the String to chomp, must not be null
3276     * @return String without chomped ending
3277     * @throws NullPointerException if str or sep is <code>null</code>
3278     * @deprecated Use {@link #chomp(String,String)} instead.
3279     * Method will be removed in Commons Lang 3.0.
3280     */

3281    public static String JavaDoc chompLast(String JavaDoc str, String JavaDoc sep) {
3282        if (str.length() == 0) {
3283            return str;
3284        }
3285        String JavaDoc sub = str.substring(str.length() - sep.length());
3286        if (sep.equals(sub)) {
3287            return str.substring(0, str.length() - sep.length());
3288        } else {
3289            return str;
3290        }
3291    }
3292
3293    /**
3294     * <p>Remove everything and return the last value of a supplied String, and
3295     * everything after it from a String.</p>
3296     *
3297     * @param str the String to chomp from, must not be null
3298     * @param sep the String to chomp, must not be null
3299     * @return String chomped
3300     * @throws NullPointerException if str or sep is <code>null</code>
3301     * @deprecated Use {@link #substringAfterLast(String, String)} instead
3302     * (although this doesn't include the separator)
3303     * Method will be removed in Commons Lang 3.0.
3304     */

3305    public static String JavaDoc getChomp(String JavaDoc str, String JavaDoc sep) {
3306        int idx = str.lastIndexOf(sep);
3307        if (idx == str.length() - sep.length()) {
3308            return sep;
3309        } else if (idx != -1) {
3310            return str.substring(idx);
3311        } else {
3312            return EMPTY;
3313        }
3314    }
3315
3316    /**
3317     * <p>Remove the first value of a supplied String, and everything before it
3318     * from a String.</p>
3319     *
3320     * @param str the String to chomp from, must not be null
3321     * @param sep the String to chomp, must not be null
3322     * @return String without chomped beginning
3323     * @throws NullPointerException if str or sep is <code>null</code>
3324     * @deprecated Use {@link #substringAfter(String,String)} instead.
3325     * Method will be removed in Commons Lang 3.0.
3326     */

3327    public static String JavaDoc prechomp(String JavaDoc str, String JavaDoc sep) {
3328        int idx = str.indexOf(sep);
3329        if (idx != -1) {
3330            return str.substring(idx + sep.length());
3331        } else {
3332            return str;
3333        }
3334    }
3335
3336    /**
3337     * <p>Remove and return everything before the first value of a
3338     * supplied String from another String.</p>
3339     *
3340     * @param str the String to chomp from, must not be null
3341     * @param sep the String to chomp, must not be null
3342     * @return String prechomped
3343     * @throws NullPointerException if str or sep is <code>null</code>
3344     * @deprecated Use {@link #substringBefore(String,String)} instead
3345     * (although this doesn't include the separator).
3346     * Method will be removed in Commons Lang 3.0.
3347     */

3348    public static String JavaDoc getPrechomp(String JavaDoc str, String JavaDoc sep) {
3349        int idx = str.indexOf(sep);
3350        if (idx != -1) {
3351            return str.substring(0, idx + sep.length());
3352        } else {
3353            return EMPTY;
3354        }
3355    }
3356
3357    // Chopping
3358
//-----------------------------------------------------------------------
3359
/**
3360     * <p>Remove the last character from a String.</p>
3361     *
3362     * <p>If the String ends in <code>\r\n</code>, then remove both
3363     * of them.</p>
3364     *
3365     * <pre>
3366     * StringUtils.chop(null) = null
3367     * StringUtils.chop("") = ""
3368     * StringUtils.chop("abc \r") = "abc "
3369     * StringUtils.chop("abc\n") = "abc"
3370     * StringUtils.chop("abc\r\n") = "abc"
3371     * StringUtils.chop("abc") = "ab"
3372     * StringUtils.chop("abc\nabc") = "abc\nab"
3373     * StringUtils.chop("a") = ""
3374     * StringUtils.chop("\r") = ""
3375     * StringUtils.chop("\n") = ""
3376     * StringUtils.chop("\r\n") = ""
3377     * </pre>
3378     *
3379     * @param str the String to chop last character from, may be null
3380     * @return String without last character, <code>null</code> if null String input
3381     */

3382    public static String JavaDoc chop(String JavaDoc str) {
3383        if (str == null) {
3384            return null;
3385        }
3386        int strLen = str.length();
3387        if (strLen < 2) {
3388            return EMPTY;
3389        }
3390        int lastIdx = strLen - 1;
3391        String JavaDoc ret = str.substring(0, lastIdx);
3392        char last = str.charAt(lastIdx);
3393        if (last == '\n') {
3394            if (ret.charAt(lastIdx - 1) == '\r') {
3395                return ret.substring(0, lastIdx - 1);
3396            }
3397        }
3398        return ret;
3399    }
3400
3401    /**
3402     * <p>Removes <code>\n</code> from end of a String if it's there.
3403     * If a <code>\r</code> precedes it, then remove that too.</p>
3404     *
3405     * @param str the String to chop a newline from, must not be null
3406     * @return String without newline
3407     * @throws NullPointerException if str is <code>null</code>
3408     * @deprecated Use {@link #chomp(String)} instead.
3409     * Method will be removed in Commons Lang 3.0.
3410     */

3411    public static String JavaDoc chopNewline(String JavaDoc str) {
3412        int lastIdx = str.length() - 1;
3413        if (lastIdx <= 0) {
3414            return EMPTY;
3415        }
3416        char last = str.charAt(lastIdx);
3417        if (last == '\n') {
3418            if (str.charAt(lastIdx - 1) == '\r') {
3419                lastIdx--;
3420            }
3421        } else {
3422            lastIdx++;
3423        }
3424        return str.substring(0, lastIdx);
3425    }
3426
3427    // Conversion
3428
//-----------------------------------------------------------------------
3429
/**
3430     * <p>Escapes any values it finds into their String form.</p>
3431     *
3432     * <p>So a tab becomes the characters <code>'\\'</code> and
3433     * <code>'t'</code>.</p>
3434     *
3435     * <p>As of Lang 2.0, this calls {@link StringEscapeUtils#escapeJava(String)}
3436     * behind the scenes.
3437     * </p>
3438     * @see StringEscapeUtils#escapeJava(java.lang.String)
3439     * @param str String to escape values in
3440     * @return String with escaped values
3441     * @throws NullPointerException if str is <code>null</code>
3442     * @deprecated Use {@link StringEscapeUtils#escapeJava(String)}
3443     * This method will be removed in Commons Lang 3.0
3444     */

3445    public static String JavaDoc escape(String JavaDoc str) {
3446        return StringEscapeUtils.escapeJava(str);
3447    }
3448
3449    // Padding
3450
//-----------------------------------------------------------------------
3451
/**
3452     * <p>Repeat a String <code>repeat</code> times to form a
3453     * new String.</p>
3454     *
3455     * <pre>
3456     * StringUtils.repeat(null, 2) = null
3457     * StringUtils.repeat("", 0) = ""
3458     * StringUtils.repeat("", 2) = ""
3459     * StringUtils.repeat("a", 3) = "aaa"
3460     * StringUtils.repeat("ab", 2) = "abab"
3461     * StringUtils.repeat("a", -2) = ""
3462     * </pre>
3463     *
3464     * @param str the String to repeat, may be null
3465     * @param repeat number of times to repeat str, negative treated as zero
3466     * @return a new String consisting of the original String repeated,
3467     * <code>null</code> if null String input
3468     */

3469    public static String JavaDoc repeat(String JavaDoc str, int repeat) {
3470        // Performance tuned for 2.0 (JDK1.4)
3471

3472        if (str == null) {
3473            return null;
3474        }
3475        if (repeat <= 0) {
3476            return EMPTY;
3477        }
3478        int inputLength = str.length();
3479        if (repeat == 1 || inputLength == 0) {
3480            return str;
3481        }
3482        if (inputLength == 1 && repeat <= PAD_LIMIT) {
3483            return padding(repeat, str.charAt(0));
3484        }
3485
3486        int outputLength = inputLength * repeat;
3487        switch (inputLength) {
3488            case 1 :
3489                char ch = str.charAt(0);
3490                char[] output1 = new char[outputLength];
3491                for (int i = repeat - 1; i >= 0; i--) {
3492                    output1[i] = ch;
3493                }
3494                return new String JavaDoc(output1);
3495            case 2 :
3496                char ch0 = str.charAt(0);
3497                char ch1 = str.charAt(1);
3498                char[] output2 = new char[outputLength];
3499                for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
3500                    output2[i] = ch0;
3501                    output2[i + 1] = ch1;
3502                }
3503                return new String JavaDoc(output2);
3504            default :
3505                StringBuffer JavaDoc buf = new StringBuffer JavaDoc(outputLength);
3506                for (int i = 0; i < repeat; i++) {
3507                    buf.append(str);
3508                }
3509                return buf.toString();
3510        }
3511    }
3512
3513    /**
3514     * <p>Returns padding using the specified delimiter repeated
3515     * to a given length.</p>
3516     *
3517     * <pre>
3518     * StringUtils.padding(0, 'e') = ""
3519     * StringUtils.padding(3, 'e') = "eee"
3520     * StringUtils.padding(-2, 'e') = IndexOutOfBoundsException
3521     * </pre>
3522     *
3523     * @param repeat number of times to repeat delim
3524     * @param padChar character to repeat
3525     * @return String with repeated character
3526     * @throws IndexOutOfBoundsException if <code>repeat &lt; 0</code>
3527     */

3528    private static String JavaDoc padding(int repeat, char padChar) {
3529        // be careful of synchronization in this method
3530
// we are assuming that get and set from an array index is atomic
3531
String JavaDoc pad = PADDING[padChar];
3532        if (pad == null) {
3533            pad = String.valueOf(padChar);
3534        }
3535        while (pad.length() < repeat) {
3536            pad = pad.concat(pad);
3537        }
3538        PADDING[padChar] = pad;
3539        return pad.substring(0, repeat);
3540    }
3541
3542    /**
3543     * <p>Right pad a String with spaces (' ').</p>
3544     *
3545     * <p>The String is padded to the size of <code>size</code>.</p>
3546     *
3547     * <pre>
3548     * StringUtils.rightPad(null, *) = null
3549     * StringUtils.rightPad("", 3) = " "
3550     * StringUtils.rightPad("bat", 3) = "bat"
3551     * StringUtils.rightPad("bat", 5) = "bat "
3552     * StringUtils.rightPad("bat", 1) = "bat"
3553     * StringUtils.rightPad("bat", -1) = "bat"
3554     * </pre>
3555     *
3556     * @param str the String to pad out, may be null
3557     * @param size the size to pad to
3558     * @return right padded String or original String if no padding is necessary,
3559     * <code>null</code> if null String input
3560     */

3561    public static String JavaDoc rightPad(String JavaDoc str, int size) {
3562        return rightPad(str, size, ' ');
3563    }
3564
3565    /**
3566     * <p>Right pad a String with a specified character.</p>
3567     *
3568     * <p>The String is padded to the size of <code>size</code>.</p>
3569     *
3570     * <pre>
3571     * StringUtils.rightPad(null, *, *) = null
3572     * StringUtils.rightPad("", 3, 'z') = "zzz"
3573     * StringUtils.rightPad("bat", 3, 'z') = "bat"
3574     * StringUtils.rightPad("bat", 5, 'z') = "batzz"
3575     * StringUtils.rightPad("bat", 1, 'z') = "bat"
3576     * StringUtils.rightPad("bat", -1, 'z') = "bat"
3577     * </pre>
3578     *
3579     * @param str the String to pad out, may be null
3580     * @param size the size to pad to
3581     * @param padChar the character to pad with
3582     * @return right padded String or original String if no padding is necessary,
3583     * <code>null</code> if null String input
3584     * @since 2.0
3585     */

3586    public static String JavaDoc rightPad(String JavaDoc str, int size, char padChar) {
3587        if (str == null) {
3588            return null;
3589        }
3590        int pads = size - str.length();
3591        if (pads <= 0) {
3592            return str; // returns original String when possible
3593
}
3594        if (pads > PAD_LIMIT) {
3595            return rightPad(str, size, String.valueOf(padChar));
3596        }
3597        return str.concat(padding(pads, padChar));
3598    }
3599
3600    /**
3601     * <p>Right pad a String with a specified String.</p>
3602     *
3603     * <p>The String is padded to the size of <code>size</code>.</p>
3604     *
3605     * <pre>
3606     * StringUtils.rightPad(null, *, *) = null
3607     * StringUtils.rightPad("", 3, "z") = "zzz"
3608     * StringUtils.rightPad("bat", 3, "yz") = "bat"
3609     * StringUtils.rightPad("bat", 5, "yz") = "batyz"
3610     * StringUtils.rightPad("bat", 8, "yz") = "batyzyzy"
3611     * StringUtils.rightPad("bat", 1, "yz") = "bat"
3612     * StringUtils.rightPad("bat", -1, "yz") = "bat"
3613     * StringUtils.rightPad("bat", 5, null) = "bat "
3614     * StringUtils.rightPad("bat", 5, "") = "bat "
3615     * </pre>
3616     *
3617     * @param str the String to pad out, may be null
3618     * @param size the size to pad to
3619     * @param padStr the String to pad with, null or empty treated as single space
3620     * @return right padded String or original String if no padding is necessary,
3621     * <code>null</code> if null String input
3622     */

3623    public static String JavaDoc rightPad(String JavaDoc str, int size, String JavaDoc padStr) {
3624        if (str == null) {
3625            return null;
3626        }
3627        if (isEmpty(padStr)) {
3628            padStr = " ";
3629        }
3630        int padLen = padStr.length();
3631        int strLen = str.length();
3632        int pads = size - strLen;
3633        if (pads <= 0) {
3634            return str; // returns original String when possible
3635
}
3636        if (padLen == 1 && pads <= PAD_LIMIT) {
3637            return rightPad(str, size, padStr.charAt(0));
3638        }
3639
3640        if (pads == padLen) {
3641            return str.concat(padStr);
3642        } else if (pads < padLen) {
3643            return str.concat(padStr.substring(0, pads));
3644        } else {
3645            char[] padding = new char[pads];
3646            char[] padChars = padStr.toCharArray();
3647            for (int i = 0; i < pads; i++) {
3648                padding[i] = padChars[i % padLen];
3649            }
3650            return str.concat(new String JavaDoc(padding));
3651        }
3652    }
3653
3654    /**
3655     * <p>Left pad a String with spaces (' ').</p>
3656     *
3657     * <p>The String is padded to the size of <code>size<code>.</p>
3658     *
3659     * <pre>
3660     * StringUtils.leftPad(null, *) = null
3661     * StringUtils.leftPad("", 3) = " "
3662     * StringUtils.leftPad("bat", 3) = "bat"
3663     * StringUtils.leftPad("bat", 5) = " bat"
3664     * StringUtils.leftPad("bat", 1) = "bat"
3665     * StringUtils.leftPad("bat", -1) = "bat"
3666     * </pre>
3667     *
3668     * @param str the String to pad out, may be null
3669     * @param size the size to pad to
3670     * @return left padded String or original String if no padding is necessary,
3671     * <code>null</code> if null String input
3672     */

3673    public static String JavaDoc leftPad(String JavaDoc str, int size) {
3674        return leftPad(str, size, ' ');
3675    }
3676
3677    /**
3678     * <p>Left pad a String with a specified character.</p>
3679     *
3680     * <p>Pad to a size of <code>size</code>.</p>
3681     *
3682     * <pre>
3683     * StringUtils.leftPad(null, *, *) = null
3684     * StringUtils.leftPad("", 3, 'z') = "zzz"
3685     * StringUtils.leftPad("bat", 3, 'z') = "bat"
3686     * StringUtils.leftPad("bat", 5, 'z') = "zzbat"
3687     * StringUtils.leftPad("bat", 1, 'z') = "bat"
3688     * StringUtils.leftPad("bat", -1, 'z') = "bat"
3689     * </pre>
3690     *
3691     * @param str the String to pad out, may be null
3692     * @param size the size to pad to
3693     * @param padChar the character to pad with
3694     * @return left padded String or original String if no padding is necessary,
3695     * <code>null</code> if null String input
3696     * @since 2.0
3697     */

3698    public static String JavaDoc leftPad(String JavaDoc str, int size, char padChar) {
3699        if (str == null) {
3700            return null;
3701        }
3702        int pads = size - str.length();
3703        if (pads <= 0) {
3704            return str; // returns original String when possible
3705
}
3706        if (pads > PAD_LIMIT) {
3707            return leftPad(str, size, String.valueOf(padChar));
3708        }
3709        return padding(pads, padChar).concat(str);
3710    }
3711
3712    /**
3713     * <p>Left pad a String with a specified String.</p>
3714     *
3715     * <p>Pad to a size of <code>size</code>.</p>
3716     *
3717     * <pre>
3718     * StringUtils.leftPad(null, *, *) = null
3719     * StringUtils.leftPad("", 3, "z") = "zzz"
3720     * StringUtils.leftPad("bat", 3, "yz") = "bat"
3721     * StringUtils.leftPad("bat", 5, "yz") = "yzbat"
3722     * StringUtils.leftPad("bat", 8, "yz") = "yzyzybat"
3723     * StringUtils.leftPad("bat", 1, "yz") = "bat"
3724     * StringUtils.leftPad("bat", -1, "yz") = "bat"
3725     * StringUtils.leftPad("bat", 5, null) = " bat"
3726     * StringUtils.leftPad("bat", 5, "") = " bat"
3727     * </pre>
3728     *
3729     * @param str the String to pad out, may be null
3730     * @param size the size to pad to
3731     * @param padStr the String to pad with, null or empty treated as single space
3732     * @return left padded String or original String if no padding is necessary,
3733     * <code>null</code> if null String input
3734     */

3735    public static String JavaDoc leftPad(String JavaDoc str, int size, String JavaDoc padStr) {
3736        if (str == null) {
3737            return null;
3738        }
3739        if (isEmpty(padStr)) {
3740            padStr = " ";
3741        }
3742        int padLen = padStr.length();
3743        int strLen = str.length();
3744        int pads = size - strLen;
3745        if (pads <= 0) {
3746            return str; // returns original String when possible
3747
}
3748        if (padLen == 1 && pads <= PAD_LIMIT) {
3749            return leftPad(str, size, padStr.charAt(0));
3750        }
3751
3752        if (pads == padLen) {
3753            return padStr.concat(str);
3754        } else if (pads < padLen) {
3755            return padStr.substring(0, pads).concat(str);
3756        } else {
3757            char[] padding = new char[pads];
3758            char[] padChars = padStr.toCharArray();
3759            for (int i = 0; i < pads; i++) {
3760                padding[i] = padChars[i % padLen];
3761            }
3762            return new String JavaDoc(padding).concat(str);
3763        }
3764    }
3765
3766    // Centering
3767
//-----------------------------------------------------------------------
3768
/**
3769     * <p>Centers a String in a larger String of size <code>size</code>
3770     * using the space character (' ').<p>
3771     *
3772     * <p>If the size is less than the String length, the String is returned.
3773     * A <code>null</code> String returns <code>null</code>.
3774     * A negative size is treated as zero.</p>
3775     *
3776     * <p>Equivalent to <code>center(str, size, " ")</code>.</p>
3777     *
3778     * <pre>
3779     * StringUtils.center(null, *) = null
3780     * StringUtils.center("", 4) = " "
3781     * StringUtils.center("ab", -1) = "ab"
3782     * StringUtils.center("ab", 4) = " ab "
3783     * StringUtils.center("abcd", 2) = "abcd"
3784     * StringUtils.center("a", 4) = " a "
3785     * </pre>
3786     *
3787     * @param str the String to center, may be null
3788     * @param size the int size of new String, negative treated as zero
3789     * @return centered String, <code>null</code> if null String input
3790     */

3791    public static String JavaDoc center(String JavaDoc str, int size) {
3792        return center(str, size, ' ');
3793    }
3794
3795    /**
3796     * <p>Centers a String in a larger String of size <code>size</code>.
3797     * Uses a supplied character as the value to pad the String with.</p>
3798     *
3799     * <p>If the size is less than the String length, the String is returned.
3800     * A <code>null</code> String returns <code>null</code>.
3801     * A negative size is treated as zero.</p>
3802     *
3803     * <pre>
3804     * StringUtils.center(null, *, *) = null
3805     * StringUtils.center("", 4, ' ') = " "
3806     * StringUtils.center("ab", -1, ' ') = "ab"
3807     * StringUtils.center("ab", 4, ' ') = " ab"
3808     * StringUtils.center("abcd", 2, ' ') = "abcd"
3809     * StringUtils.center("a", 4, ' ') = " a "
3810     * StringUtils.center("a", 4, 'y') = "yayy"
3811     * </pre>
3812     *
3813     * @param str the String to center, may be null
3814     * @param size the int size of new String, negative treated as zero
3815     * @param padChar the character to pad the new String with
3816     * @return centered String, <code>null</code> if null String input
3817     * @since 2.0
3818     */

3819    public static String JavaDoc center(String JavaDoc str, int size, char padChar) {
3820        if (str == null || size <= 0) {
3821            return str;
3822        }
3823        int strLen = str.length();
3824        int pads = size - strLen;
3825        if (pads <= 0) {
3826            return str;
3827        }
3828        str = leftPad(str, strLen + pads / 2, padChar);
3829        str = rightPad(str, size, padChar);
3830        return str;
3831    }
3832
3833    /**
3834     * <p>Centers a String in a larger String of size <code>size</code>.
3835     * Uses a supplied String as the value to pad the String with.</p>
3836     *
3837     * <p>If the size is less than the String length, the String is returned.
3838     * A <code>null</code> String returns <code>null</code>.
3839     * A negative size is treated as zero.</p>
3840     *
3841     * <pre>
3842     * StringUtils.center(null, *, *) = null
3843     * StringUtils.center("", 4, " ") = " "
3844     * StringUtils.center("ab", -1, " ") = "ab"
3845     * StringUtils.center("ab", 4, " ") = " ab"
3846     * StringUtils.center("abcd", 2, " ") = "abcd"
3847     * StringUtils.center("a", 4, " ") = " a "
3848     * StringUtils.center("a", 4, "yz") = "yayz"
3849     * StringUtils.center("abc", 7, null) = " abc "
3850     * StringUtils.center("abc", 7, "") = " abc "
3851     * </pre>
3852     *
3853     * @param str the String to center, may be null
3854     * @param size the int size of new String, negative treated as zero
3855     * @param padStr the String to pad the new String with, must not be null or empty
3856     * @return centered String, <code>null</code> if null String input
3857     * @throws IllegalArgumentException if padStr is <code>null</code> or empty
3858     */

3859    public static String JavaDoc center(String JavaDoc str, int size, String JavaDoc padStr) {
3860        if (str == null || size <= 0) {
3861            return str;
3862        }
3863        if (isEmpty(padStr)) {
3864            padStr = " ";
3865        }
3866        int strLen = str.length();
3867        int pads = size - strLen;
3868        if (pads <= 0) {
3869            return str;
3870        }
3871        str = leftPad(str, strLen + pads / 2, padStr);
3872        str = rightPad(str, size, padStr);
3873        return str;
3874    }
3875
3876    // Case conversion
3877
//-----------------------------------------------------------------------
3878
/**
3879     * <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p>
3880     *
3881     * <p>A <code>null</code> input String returns <code>null</code>.</p>
3882     *
3883     * <pre>
3884     * StringUtils.upperCase(null) = null
3885     * StringUtils.upperCase("") = ""
3886     * StringUtils.upperCase("aBc") = "ABC"
3887     * </pre>
3888     *
3889     * @param str the String to upper case, may be null
3890     * @return the upper cased String, <code>null</code> if null String input
3891     */

3892    public static String JavaDoc upperCase(String JavaDoc str) {
3893        if (str == null) {
3894            return null;
3895        }
3896        return str.toUpperCase();
3897    }
3898
3899    /**
3900     * <p>Converts a String to lower case as per {@link String#toLowerCase()}.</p>
3901     *
3902     * <p>A <code>null</code> input String returns <code>null</code>.</p>
3903     *
3904     * <pre>
3905     * StringUtils.lowerCase(null) = null
3906     * StringUtils.lowerCase("") = ""
3907     * StringUtils.lowerCase("aBc") = "abc"
3908     * </pre>
3909     *
3910     * @param str the String to lower case, may be null
3911     * @return the lower cased String, <code>null</code> if null String input
3912     */

3913    public static String JavaDoc lowerCase(String JavaDoc str) {
3914        if (str == null) {
3915            return null;
3916        }
3917        return str.toLowerCase();
3918    }
3919
3920    /**
3921     * <p>Capitalizes a String changing the first letter to title case as
3922     * per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
3923     *
3924     * <p>For a word based algorithm, see {@link WordUtils#capitalize(String)}.
3925     * A <code>null</code> input String returns <code>null</code>.</p>
3926     *
3927     * <pre>
3928     * StringUtils.capitalize(null) = null
3929     * StringUtils.capitalize("") = ""
3930     * StringUtils.capitalize("cat") = "Cat"
3931     * StringUtils.capitalize("cAt") = "CAt"
3932     * </pre>
3933     *
3934     * @param str the String to capitalize, may be null
3935     * @return the capitalized String, <code>null</code> if null String input
3936     * @see WordUtils#capitalize(String)
3937     * @see #uncapitalize(String)
3938     * @since 2.0
3939     */

3940    public static String JavaDoc capitalize(String JavaDoc str) {
3941        int strLen;
3942        if (str == null || (strLen = str.length()) == 0) {
3943            return str;
3944        }
3945        return new StringBuffer JavaDoc(strLen)
3946            .append(Character.toTitleCase(str.charAt(0)))
3947            .append(str.substring(1))
3948            .toString();
3949    }
3950
3951    /**
3952     * <p>Capitalizes a String changing the first letter to title case as
3953     * per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
3954     *
3955     * @param str the String to capitalize, may be null
3956     * @return the capitalized String, <code>null</code> if null String input
3957     * @deprecated Use the standardly named {@link #capitalize(String)}.
3958     * Method will be removed in Commons Lang 3.0.
3959     */

3960    public static String JavaDoc capitalise(String JavaDoc str) {
3961        return capitalize(str);
3962    }
3963
3964    /**
3965     * <p>Uncapitalizes a String changing the first letter to title case as
3966     * per {@link Character#toLowerCase(char)}. No other letters are changed.</p>
3967     *
3968     * <p>For a word based algorithm, see {@link WordUtils#uncapitalize(String)}.
3969     * A <code>null</code> input String returns <code>null</code>.</p>
3970     *
3971     * <pre>
3972     * StringUtils.uncapitalize(null) = null
3973     * StringUtils.uncapitalize("") = ""
3974     * StringUtils.uncapitalize("Cat") = "cat"
3975     * StringUtils.uncapitalize("CAT") = "cAT"
3976     * </pre>
3977     *
3978     * @param str the String to uncapitalize, may be null
3979     * @return the uncapitalized String, <code>null</code> if null String input
3980     * @see WordUtils#uncapitalize(String)
3981     * @see #capitalize(String)
3982     * @since 2.0
3983     */

3984    public static String JavaDoc uncapitalize(String JavaDoc str) {
3985        int strLen;
3986        if (str == null || (strLen = str.length()) == 0) {
3987            return str;
3988        }
3989        return new StringBuffer JavaDoc(strLen)
3990            .append(Character.toLowerCase(str.charAt(0)))
3991            .append(str.substring(1))
3992            .toString();
3993    }
3994
3995    /**
3996     * <p>Uncapitalizes a String changing the first letter to title case as
3997     * per {@link Character#toLowerCase(char)}. No other letters are changed.</p>
3998     *
3999     * @param str the String to uncapitalize, may be null
4000     * @return the uncapitalized String, <code>null</code> if null String input
4001     * @deprecated Use the standardly named {@link #uncapitalize(String)}.
4002     * Method will be removed in Commons Lang 3.0.
4003     */

4004    public static String JavaDoc uncapitalise(String JavaDoc str) {
4005        return uncapitalize(str);
4006    }
4007
4008    /**
4009     * <p>Swaps the case of a String changing upper and title case to
4010     * lower case, and lower case to upper case.</p>
4011     *
4012     * <ul>
4013     * <li>Upper case character converts to Lower case</li>
4014     * <li>Title case character converts to Lower case</li>
4015     * <li>Lower case character converts to Upper case</li>
4016     * </ul>
4017     *
4018     * <p>For a word based algorithm, see {@link WordUtils#swapCase(String)}.
4019     * A <code>null</code> input String returns <code>null</code>.</p>
4020     *
4021     * <pre>
4022     * StringUtils.swapCase(null) = null
4023     * StringUtils.swapCase("") = ""
4024     * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
4025     * </pre>
4026     *
4027     * <p>NOTE: This method changed in Lang version 2.0.
4028     * It no longer performs a word based algorithm.
4029     * If you only use ASCII, you will notice no change.
4030     * That functionality is available in WordUtils.</p>
4031     *
4032     * @param str the String to swap case, may be null
4033     * @return the changed String, <code>null</code> if null String input
4034     */

4035    public static String JavaDoc swapCase(String JavaDoc str) {
4036        int strLen;
4037        if (str == null || (strLen = str.length()) == 0) {
4038            return str;
4039        }
4040        StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(strLen);
4041
4042        char ch = 0;
4043        for (int i = 0; i < strLen; i++) {
4044            ch = str.charAt(i);
4045            if (Character.isUpperCase(ch)) {
4046                ch = Character.toLowerCase(ch);
4047            } else if (Character.isTitleCase(ch)) {
4048                ch = Character.toLowerCase(ch);
4049            } else if (Character.isLowerCase(ch)) {
4050                ch = Character.toUpperCase(ch);
4051            }
4052            buffer.append(ch);
4053        }
4054        return buffer.toString();
4055    }
4056
4057    /**
4058     * <p>Capitalizes all the whitespace separated words in a String.
4059     * Only the first letter of each word is changed.</p>
4060     *
4061     * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.
4062     * A <code>null</code> input String returns <code>null</code>.</p>
4063     *
4064     * @param str the String to capitalize, may be null
4065     * @return capitalized String, <code>null</code> if null String input
4066     * @deprecated Use the relocated {@link WordUtils#capitalize(String)}.
4067     * Method will be removed in Commons Lang 3.0.
4068     */

4069    public static String JavaDoc capitaliseAllWords(String JavaDoc str) {
4070        return WordUtils.capitalize(str);
4071    }
4072
4073    // Count matches
4074
//-----------------------------------------------------------------------
4075
/**
4076     * <p>Counts how many times the substring appears in the larger String.</p>
4077     *
4078     * <p>A <code>null</code> or empty ("") String input returns <code>0</code>.</p>
4079     *
4080     * <pre>
4081     * StringUtils.countMatches(null, *) = 0
4082     * StringUtils.countMatches("", *) = 0
4083     * StringUtils.countMatches("abba", null) = 0
4084     * StringUtils.countMatches("abba", "") = 0
4085     * StringUtils.countMatches("abba", "a") = 2
4086     * StringUtils.countMatches("abba", "ab") = 1
4087     * StringUtils.countMatches("abba", "xxx") = 0
4088     * </pre>
4089     *
4090     * @param str the String to check, may be null
4091     * @param sub the substring to count, may be null
4092     * @return the number of occurrences, 0 if either String is <code>null</code>
4093     */

4094    public static int countMatches(String JavaDoc str, String JavaDoc sub) {
4095        if (isEmpty(str) || isEmpty(sub)) {
4096            return 0;
4097        }
4098        int count = 0;
4099        int idx = 0;
4100        while ((idx = str.indexOf(sub, idx)) != -1) {
4101            count++;
4102            idx += sub.length();
4103        }
4104        return count;
4105    }
4106
4107    // Character Tests
4108
//-----------------------------------------------------------------------
4109
/**
4110     * <p>Checks if the String contains only unicode letters.</p>
4111     *
4112     * <p><code>null</code> will return <code>false</code>.
4113     * An empty String ("") will return <code>true</code>.</p>
4114     *
4115     * <pre>
4116     * StringUtils.isAlpha(null) = false
4117     * StringUtils.isAlpha("") = true
4118     * StringUtils.isAlpha(" ") = false
4119     * StringUtils.isAlpha("abc") = true
4120     * StringUtils.isAlpha("ab2c") = false
4121     * StringUtils.isAlpha("ab-c") = false
4122     * </pre>
4123     *
4124     * @param str the String to check, may be null
4125     * @return <code>true</code> if only contains letters, and is non-null
4126     */

4127    public static boolean isAlpha(String JavaDoc str) {
4128        if (str == null) {
4129            return false;
4130        }
4131        int sz = str.length();
4132        for (int i = 0; i < sz; i++) {
4133            if (Character.isLetter(str.charAt(i)) == false) {
4134                return false;
4135            }
4136        }
4137        return true;
4138    }
4139
4140    /**
4141     * <p>Checks if the String contains only unicode letters and
4142     * space (' ').</p>
4143     *
4144     * <p><code>null</code> will return <code>false</code>
4145     * An empty String ("") will return <code>true</code>.</p>
4146     *
4147     * <pre>
4148     * StringUtils.isAlphaSpace(null) = false
4149     * StringUtils.isAlphaSpace("") = true
4150     * StringUtils.isAlphaSpace(" ") = true
4151     * StringUtils.isAlphaSpace("abc") = true
4152     * StringUtils.isAlphaSpace("ab c") = true
4153     * StringUtils.isAlphaSpace("ab2c") = false
4154     * StringUtils.isAlphaSpace("ab-c") = false
4155     * </pre>
4156     *
4157     * @param str the String to check, may be null
4158     * @return <code>true</code> if only contains letters and space,
4159     * and is non-null
4160     */

4161    public static boolean isAlphaSpace(String JavaDoc str) {
4162        if (str == null) {
4163            return false;
4164        }
4165        int sz = str.length();
4166        for (int i = 0; i < sz; i++) {
4167            if ((Character.isLetter(str.charAt(i)) == false) && (str.charAt(i) != ' ')) {
4168                return false;
4169            }
4170        }
4171        return true;
4172    }
4173
4174    /**
4175     * <p>Checks if the String contains only unicode letters or digits.</p>
4176     *
4177     * <p><code>null</code> will return <code>false</code>.
4178     * An empty String ("") will return <code>true</code>.</p>
4179     *
4180     * <pre>
4181     * StringUtils.isAlphanumeric(null) = false
4182     * StringUtils.isAlphanumeric("") = true
4183     * StringUtils.isAlphanumeric(" ") = false
4184     * StringUtils.isAlphanumeric("abc") = true
4185     * StringUtils.isAlphanumeric("ab c") = false
4186     * StringUtils.isAlphanumeric("ab2c") = true
4187     * StringUtils.isAlphanumeric("ab-c") = false
4188     * </pre>
4189     *
4190     * @param str the String to check, may be null
4191     * @return <code>true</code> if only contains letters or digits,
4192     * and is non-null
4193     */

4194    public static boolean isAlphanumeric(String JavaDoc str) {
4195        if (str == null) {
4196            return false;
4197        }
4198        int sz = str.length();
4199        for (int i = 0; i < sz; i++) {
4200            if (Character.isLetterOrDigit(str.charAt(i)) == false) {
4201                return false;
4202            }
4203        }
4204        return true;
4205    }
4206
4207    /**
4208     * <p>Checks if the String contains only unicode letters, digits
4209     * or space (<code>' '</code>).</p>
4210     *
4211     * <p><code>null</code> will return <code>false</code>.
4212     * An empty String ("") will return <code>true</code>.</p>
4213     *
4214     * <pre>
4215     * StringUtils.isAlphanumeric(null) = false
4216     * StringUtils.isAlphanumeric("") = true
4217     * StringUtils.isAlphanumeric(" ") = true
4218     * StringUtils.isAlphanumeric("abc") = true
4219     * StringUtils.isAlphanumeric("ab c") = true
4220     * StringUtils.isAlphanumeric("ab2c") = true
4221     * StringUtils.isAlphanumeric("ab-c") = false
4222     * </pre>
4223     *
4224     * @param str the String to check, may be null
4225     * @return <code>true</code> if only contains letters, digits or space,
4226     * and is non-null
4227     */

4228    public static boolean isAlphanumericSpace(String JavaDoc str) {
4229        if (str == null) {
4230            return false;
4231        }
4232        int sz = str.length();
4233        for (int i = 0; i < sz; i++) {
4234            if ((Character.isLetterOrDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) {
4235                return false;
4236            }
4237        }
4238        return true;
4239    }
4240
4241    /**
4242     * <p>Checks if the string contains only ASCII printable characters.</p>
4243     *
4244     * <p><code>null</code> will return <code>false</code>.
4245     * An empty String ("") will return <code>true</code>.</p>
4246     *
4247     * <pre>
4248     * StringUtils.isAsciiPrintable(null) = false
4249     * StringUtils.isAsciiPrintable("") = true
4250     * StringUtils.isAsciiPrintable(" ") = true
4251     * StringUtils.isAsciiPrintable("Ceki") = true
4252     * StringUtils.isAsciiPrintable("ab2c") = true
4253     * StringUtils.isAsciiPrintable("!ab-c~") = true
4254     * StringUtils.isAsciiPrintable(" ") = true
4255     * StringUtils.isAsciiPrintable("!") = true
4256     * StringUtils.isAsciiPrintable("~") = true
4257     * StringUtils.isAsciiPrintable("") = false
4258     * StringUtils.isAsciiPrintable("Ceki Gülcü") = false
4259     * </pre>
4260     *
4261     * @param str the string to check, may be null
4262     * @return <code>true</code> if every character is in the range
4263     * 32 thru 126
4264     * @since 2.1
4265     */

4266    public static boolean isAsciiPrintable(String JavaDoc str) {
4267        if (str == null) {
4268            return false;
4269        }
4270        int sz = str.length();
4271        for (int i = 0; i < sz; i++) {
4272            if (CharUtils.isAsciiPrintable(str.charAt(i)) == false) {
4273                return false;
4274            }
4275        }
4276        return true;
4277    }
4278  
4279    /**
4280     * <p>Checks if the String contains only unicode digits.
4281     * A decimal point is not a unicode digit and returns false.</p>
4282     *
4283     * <p><code>null</code> will return <code>false</code>.
4284     * An empty String ("") will return <code>true</code>.</p>
4285     *
4286     * <pre>
4287     * StringUtils.isNumeric(null) = false
4288     * StringUtils.isNumeric("") = true
4289     * StringUtils.isNumeric(" ") = false
4290     * StringUtils.isNumeric("123") = true
4291     * StringUtils.isNumeric("12 3") = false
4292     * StringUtils.isNumeric("ab2c") = false
4293     * StringUtils.isNumeric("12-3") = false
4294     * StringUtils.isNumeric("12.3") = false
4295     * </pre>
4296     *
4297     * @param str the String to check, may be null
4298     * @return <code>true</code> if only contains digits, and is non-null
4299     */

4300    public static boolean isNumeric(String JavaDoc str) {
4301        if (str == null) {
4302            return false;
4303        }
4304        int sz = str.length();
4305        for (int i = 0; i < sz; i++) {
4306            if (Character.isDigit(str.charAt(i)) == false) {
4307                return false;
4308            }
4309        }
4310        return true;
4311    }
4312
4313    /**
4314     * <p>Checks if the String contains only unicode digits or space
4315     * (<code>' '</code>).
4316     * A decimal point is not a unicode digit and returns false.</p>
4317     *
4318     * <p><code>null</code> will return <code>false</code>.
4319     * An empty String ("") will return <code>true</code>.</p>
4320     *
4321     * <pre>
4322     * StringUtils.isNumeric(null) = false
4323     * StringUtils.isNumeric("") = true
4324     * StringUtils.isNumeric(" ") = true
4325     * StringUtils.isNumeric("123") = true
4326     * StringUtils.isNumeric("12 3") = true
4327     * StringUtils.isNumeric("ab2c") = false
4328     * StringUtils.isNumeric("12-3") = false
4329     * StringUtils.isNumeric("12.3") = false
4330     * </pre>
4331     *
4332     * @param str the String to check, may be null
4333     * @return <code>true</code> if only contains digits or space,
4334     * and is non-null
4335     */

4336    public static boolean isNumericSpace(String JavaDoc str) {
4337        if (str == null) {
4338            return false;
4339        }
4340        int sz = str.length();
4341        for (int i = 0; i < sz; i++) {
4342            if ((Character.isDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) {
4343                return false;
4344            }
4345        }
4346        return true;
4347    }
4348
4349    /**
4350     * <p>Checks if the String contains only whitespace.</p>
4351     *
4352     * <p><code>null</code> will return <code>false</code>.
4353     * An empty String ("") will return <code>true</code>.</p>
4354     *
4355     * <pre>
4356     * StringUtils.isWhitespace(null) = false
4357     * StringUtils.isWhitespace("") = true
4358     * StringUtils.isWhitespace(" ") = true
4359     * StringUtils.isWhitespace("abc") = false
4360     * StringUtils.isWhitespace("ab2c") = false
4361     * StringUtils.isWhitespace("ab-c") = false
4362     * </pre>
4363     *
4364     * @param str the String to check, may be null
4365     * @return <code>true</code> if only contains whitespace, and is non-null
4366     * @since 2.0
4367     */

4368    public static boolean isWhitespace(String JavaDoc str) {
4369        if (str == null) {
4370            return false;
4371        }
4372        int sz = str.length();
4373        for (int i = 0; i < sz; i++) {
4374            if ((Character.isWhitespace(str.charAt(i)) == false)) {
4375                return false;
4376            }
4377        }
4378        return true;
4379    }
4380
4381    // Defaults
4382
//-----------------------------------------------------------------------
4383
/**
4384     * <p>Returns either the passed in String,
4385     * or if the String is <code>null</code>, an empty String ("").</p>
4386     *
4387     * <pre>
4388     * StringUtils.defaultString(null) = ""
4389     * StringUtils.defaultString("") = ""
4390     * StringUtils.defaultString("bat") = "bat"
4391     * </pre>
4392     *
4393     * @see ObjectUtils#toString(Object)
4394     * @see String#valueOf(Object)
4395     * @param str the String to check, may be null
4396     * @return the passed in String, or the empty String if it
4397     * was <code>null</code>
4398     */

4399    public static String JavaDoc defaultString(String JavaDoc str) {
4400        return str == null ? EMPTY : str;
4401    }
4402
4403    /**
4404     * <p>Returns either the passed in String, or if the String is
4405     * <code>null</code>, the value of <code>defaultStr</code>.</p>
4406     *
4407     * <pre>
4408     * StringUtils.defaultString(null, "NULL") = "NULL"
4409     * StringUtils.defaultString("", "NULL") = ""
4410     * StringUtils.defaultString("bat", "NULL") = "bat"
4411     * </pre>
4412     *
4413     * @see ObjectUtils#toString(Object,String)
4414     * @see String#valueOf(Object)
4415     * @param str the String to check, may be null
4416     * @param defaultStr the default String to return
4417     * if the input is <code>null</code>, may be null
4418     * @return the passed in String, or the default if it was <code>null</code>
4419     */

4420    public static String JavaDoc defaultString(String JavaDoc str, String JavaDoc defaultStr) {
4421        return str == null ? defaultStr : str;
4422    }
4423
4424    /**
4425     * <p>Returns either the passed in String, or if the String is
4426     * empty or <code>null</code>, the value of <code>defaultStr</code>.</p>
4427     *
4428     * <pre>
4429     * StringUtils.defaultIfEmpty(null, "NULL") = "NULL"
4430     * StringUtils.defaultIfEmpty("", "NULL") = "NULL"
4431     * StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
4432     * </pre>
4433     *
4434     * @see StringUtils#defaultString(String, String)
4435     * @param str the String to check, may be null
4436     * @param defaultStr the default String to return
4437     * if the input is empty ("") or <code>null</code>, may be null
4438     * @return the passed in String, or the default
4439     */

4440    public static String JavaDoc defaultIfEmpty(String JavaDoc str, String JavaDoc defaultStr) {
4441        return StringUtils.isEmpty(str) ? defaultStr : str;
4442    }
4443
4444    // Reversing
4445
//-----------------------------------------------------------------------
4446
/**
4447     * <p>Reverses a String as per {@link StringBuffer#reverse()}.</p>
4448     *
4449     * <p>A <code>null</code> String returns <code>null</code>.</p>
4450     *
4451     * <pre>
4452     * StringUtils.reverse(null) = null
4453     * StringUtils.reverse("") = ""
4454     * StringUtils.reverse("bat") = "tab"
4455     * </pre>
4456     *
4457     * @param str the String to reverse, may be null
4458     * @return the reversed String, <code>null</code> if null String input
4459     */

4460    public static String JavaDoc reverse(String JavaDoc str) {
4461        if (str == null) {
4462            return null;
4463        }
4464        return new StringBuffer JavaDoc(str).reverse().toString();
4465    }
4466
4467    /**
4468     * <p>Reverses a String that is delimited by a specific character.</p>
4469     *
4470     * <p>The Strings between the delimiters are not reversed.
4471     * Thus java.lang.String becomes String.lang.java (if the delimiter
4472     * is <code>'.'</code>).</p>
4473     *
4474     * <pre>
4475     * StringUtils.reverseDelimited(null, *) = null
4476     * StringUtils.reverseDelimited("", *) = ""
4477     * StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
4478     * StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
4479     * </pre>
4480     *
4481     * @param str the String to reverse, may be null
4482     * @param separatorChar the separator character to use
4483     * @return the reversed String, <code>null</code> if null String input
4484     * @since 2.0
4485     */

4486    public static String JavaDoc reverseDelimited(String JavaDoc str, char separatorChar) {
4487        if (str == null) {
4488            return null;
4489        }
4490        // could implement manually, but simple way is to reuse other,
4491
// probably slower, methods.
4492
String JavaDoc[] strs = split(str, separatorChar);
4493        ArrayUtils.reverse(strs);
4494        return join(strs, separatorChar);
4495    }
4496
4497    /**
4498     * <p>Reverses a String that is delimited by a specific character.</p>
4499     *
4500     * <p>The Strings between the delimiters are not reversed.
4501     * Thus java.lang.String becomes String.lang.java (if the delimiter
4502     * is <code>"."</code>).</p>
4503     *
4504     * <pre>
4505     * StringUtils.reverseDelimitedString(null, *) = null
4506     * StringUtils.reverseDelimitedString("",*) = ""
4507     * StringUtils.reverseDelimitedString("a.b.c", null) = "a.b.c"
4508     * StringUtils.reverseDelimitedString("a.b.c", ".") = "c.b.a"
4509     * </pre>
4510     *
4511     * @param str the String to reverse, may be null
4512     * @param separatorChars the separator characters to use, null treated as whitespace
4513     * @return the reversed String, <code>null</code> if null String input
4514     * @deprecated Use {@link #reverseDelimited(String, char)} instead.
4515     * This method is broken as the join doesn't know which char to use.
4516     * Method will be removed in Commons Lang 3.0.
4517     *
4518     */

4519    public static String JavaDoc reverseDelimitedString(String JavaDoc str, String JavaDoc separatorChars) {
4520        if (str == null) {
4521            return null;
4522        }
4523        // could implement manually, but simple way is to reuse other,
4524
// probably slower, methods.
4525
String JavaDoc[] strs = split(str, separatorChars);
4526        ArrayUtils.reverse(strs);
4527        if (separatorChars == null) {
4528            return join(strs, ' ');
4529        }
4530        return join(strs, separatorChars);
4531    }
4532
4533    // Abbreviating
4534
//-----------------------------------------------------------------------
4535
/**
4536     * <p>Abbreviates a String using ellipses. This will turn
4537     * "Now is the time for all good men" into "Now is the time for..."</p>
4538     *
4539     * <p>Specifically:
4540     * <ul>
4541     * <li>If <code>str</code> is less than <code>maxWidth</code> characters
4542     * long, return it.</li>
4543     * <li>Else abbreviate it to <code>(substring(str, 0, max-3) + "...")</code>.</li>
4544     * <li>If <code>maxWidth</code> is less than <code>4</code>, throw an
4545     * <code>IllegalArgumentException</code>.</li>
4546     * <li>In no case will it return a String of length greater than
4547     * <code>maxWidth</code>.</li>
4548     * </ul>
4549     * </p>
4550     *
4551     * <pre>
4552     * StringUtils.abbreviate(null, *) = null
4553     * StringUtils.abbreviate("", 4) = ""
4554     * StringUtils.abbreviate("abcdefg", 6) = "abc..."
4555     * StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
4556     * StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
4557     * StringUtils.abbreviate("abcdefg", 4) = "a..."
4558     * StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
4559     * </pre>
4560     *
4561     * @param str the String to check, may be null
4562     * @param maxWidth maximum length of result String, must be at least 4
4563     * @return abbreviated String, <code>null</code> if null String input
4564     * @throws IllegalArgumentException if the width is too small
4565     * @since 2.0
4566     */

4567    public static String JavaDoc abbreviate(String JavaDoc str, int maxWidth) {
4568        return abbreviate(str, 0, maxWidth);
4569    }
4570
4571    /**
4572     * <p>Abbreviates a String using ellipses. This will turn
4573     * "Now is the time for all good men" into "...is the time for..."</p>
4574     *
4575     * <p>Works like <code>abbreviate(String, int)</code>, but allows you to specify
4576     * a "left edge" offset. Note that this left edge is not necessarily going to
4577     * be the leftmost character in the result, or the first character following the
4578     * ellipses, but it will appear somewhere in the result.
4579     *
4580     * <p>In no case will it return a String of length greater than
4581     * <code>maxWidth</code>.</p>
4582     *
4583     * <pre>
4584     * StringUtils.abbreviate(null, *, *) = null
4585     * StringUtils.abbreviate("", 0, 4) = ""
4586     * StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
4587     * StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..."
4588     * StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..."
4589     * StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..."
4590     * StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..."
4591     * StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..."
4592     * StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno"
4593     * StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
4594     * StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
4595     * StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException
4596     * StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException
4597     * </pre>
4598     *
4599     * @param str the String to check, may be null
4600     * @param offset left edge of source String
4601     * @param maxWidth maximum length of result String, must be at least 4
4602     * @return abbreviated String, <code>null</code> if null String input
4603     * @throws IllegalArgumentException if the width is too small
4604     * @since 2.0
4605     */

4606    public static String JavaDoc abbreviate(String JavaDoc str, int offset, int maxWidth) {
4607        if (str == null) {
4608            return null;
4609        }
4610        if (maxWidth < 4) {
4611            throw new IllegalArgumentException JavaDoc("Minimum abbreviation width is 4");
4612        }
4613        if (str.length() <= maxWidth) {
4614            return str;
4615        }
4616        if (offset > str.length()) {
4617            offset = str.length();
4618        }
4619        if ((str.length() - offset) < (maxWidth - 3)) {
4620            offset = str.length() - (maxWidth - 3);
4621        }
4622        if (offset <= 4) {
4623            return str.substring(0, maxWidth - 3) + "...";
4624        }
4625        if (maxWidth < 7) {
4626            throw new IllegalArgumentException JavaDoc("Minimum abbreviation width with offset is 7");
4627        }
4628        if ((offset + (maxWidth - 3)) < str.length()) {
4629            return "..." + abbreviate(str.substring(offset), maxWidth - 3);
4630        }
4631        return "..." + str.substring(str.length() - (maxWidth - 3));
4632    }
4633
4634    // Difference
4635
//-----------------------------------------------------------------------
4636
/**
4637     * <p>Compares two Strings, and returns the portion where they differ.
4638     * (More precisely, return the remainder of the second String,
4639     * starting from where it's different from the first.)</p>
4640     *
4641     * <p>For example,
4642     * <code>difference("i am a machine", "i am a robot") -> "robot"</code>.</p>
4643     *
4644     * <pre>
4645     * StringUtils.difference(null, null) = null
4646     * StringUtils.difference("", "") = ""
4647     * StringUtils.difference("", "abc") = "abc"
4648     * StringUtils.difference("abc", "") = ""
4649     * StringUtils.difference("abc", "abc") = ""
4650     * StringUtils.difference("ab", "abxyz") = "xyz"
4651     * StringUtils.difference("abcde", "abxyz") = "xyz"
4652     * StringUtils.difference("abcde", "xyz") = "xyz"
4653     * </pre>
4654     *
4655     * @param str1 the first String, may be null
4656     * @param str2 the second String, may be null
4657     * @return the portion of str2 where it differs from str1; returns the
4658     * empty String if they are equal
4659     * @since 2.0
4660     */

4661    public static String JavaDoc difference(String JavaDoc str1, String JavaDoc str2) {
4662        if (str1 == null) {
4663            return str2;
4664        }
4665        if (str2 == null) {
4666            return str1;
4667        }
4668        int at = indexOfDifference(str1, str2);
4669        if (at == -1) {
4670            return EMPTY;
4671        }
4672        return str2.substring(at);
4673    }
4674
4675    /**
4676     * <p>Compares two Strings, and returns the index at which the
4677     * Strings begin to differ.</p>
4678     *
4679     * <p>For example,
4680     * <code>indexOfDifference("i am a machine", "i am a robot") -> 7</code></p>
4681     *
4682     * <pre>
4683     * StringUtils.indexOfDifference(null, null) = -1
4684     * StringUtils.indexOfDifference("", "") = -1
4685     * StringUtils.indexOfDifference("", "abc") = 0
4686     * StringUtils.indexOfDifference("abc", "") = 0
4687     * StringUtils.indexOfDifference("abc", "abc") = -1
4688     * StringUtils.indexOfDifference("ab", "abxyz") = 2
4689     * StringUtils.indexOfDifference("abcde", "abxyz") = 2
4690     * StringUtils.indexOfDifference("abcde", "xyz") = 0
4691     * </pre>
4692     *
4693     * @param str1 the first String, may be null
4694     * @param str2 the second String, may be null
4695     * @return the index where str2 and str1 begin to differ; -1 if they are equal
4696     * @since 2.0
4697     */

4698    public static int indexOfDifference(String JavaDoc str1, String JavaDoc str2) {
4699        if (str1 == str2) {
4700            return -1;
4701        }
4702        if (str1 == null || str2 == null) {
4703            return 0;
4704        }
4705        int i;
4706        for (i = 0; i < str1.length() && i < str2.length(); ++i) {
4707            if (str1.charAt(i) != str2.charAt(i)) {
4708                break;
4709            }
4710        }
4711        if (i < str2.length() || i < str1.length()) {
4712            return i;
4713        }
4714        return -1;
4715    }
4716
4717    // Misc
4718
//-----------------------------------------------------------------------
4719
/**
4720     * <p>Find the Levenshtein distance between two Strings.</p>
4721     *
4722     * <p>This is the number of changes needed to change one String into
4723     * another, where each change is a single character modification (deletion,
4724     * insertion or substitution).</p>
4725     *
4726     * <p>This implementation of the Levenshtein distance algorithm
4727     * is from <a HREF="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
4728     *
4729     * <pre>
4730     * StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
4731     * StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
4732     * StringUtils.getLevenshteinDistance("","") = 0
4733     * StringUtils.getLevenshteinDistance("","a") = 1
4734     * StringUtils.getLevenshteinDistance("aaapppp", "") = 7
4735     * StringUtils.getLevenshteinDistance("frog", "fog") = 1
4736     * StringUtils.getLevenshteinDistance("fly", "ant") = 3
4737     * StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
4738     * StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
4739     * StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
4740     * StringUtils.getLevenshteinDistance("hello", "hallo") = 1
4741     * </pre>
4742     *
4743     * @param s the first String, must not be null
4744     * @param t the second String, must not be null
4745     * @return result distance
4746     * @throws IllegalArgumentException if either String input <code>null</code>
4747     */

4748    public static int getLevenshteinDistance(String JavaDoc s, String JavaDoc t) {
4749        if (s == null || t == null) {
4750            throw new IllegalArgumentException JavaDoc("Strings must not be null");
4751        }
4752        int d[][]; // matrix
4753
int n; // length of s
4754
int m; // length of t
4755
int i; // iterates through s
4756
int j; // iterates through t
4757
char s_i; // ith character of s
4758
char t_j; // jth character of t
4759
int cost; // cost
4760

4761        // Step 1
4762
n = s.length();
4763        m = t.length();
4764        if (n == 0) {
4765            return m;
4766        }
4767        if (m == 0) {
4768            return n;
4769        }
4770        d = new int[n + 1][m + 1];
4771
4772        // Step 2
4773
for (i = 0; i <= n; i++) {
4774            d[i][0] = i;
4775        }
4776
4777        for (j = 0; j <= m; j++) {
4778            d[0][j] = j;
4779        }
4780
4781        // Step 3
4782
for (i = 1; i <= n; i++) {
4783            s_i = s.charAt(i - 1);
4784
4785            // Step 4
4786
for (j = 1; j <= m; j++) {
4787                t_j = t.charAt(j - 1);
4788
4789                // Step 5
4790
if (s_i == t_j) {
4791                    cost = 0;
4792                } else {
4793                    cost = 1;
4794                }
4795
4796                // Step 6
4797
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
4798            }
4799        }
4800
4801        // Step 7
4802
return d[n][m];
4803    }
4804
4805    /**
4806     * <p>Gets the minimum of three <code>int</code> values.</p>
4807     *
4808     * @param a value 1
4809     * @param b value 2
4810     * @param c value 3
4811     * @return the smallest of the values
4812     */

4813    private static int min(int a, int b, int c) {
4814        // Method copied from NumberUtils to avoid dependency on subpackage
4815
if (b < a) {
4816            a = b;
4817        }
4818        if (c < a) {
4819            a = c;
4820        }
4821        return a;
4822    }
4823
4824}
4825
Popular Tags