2 * Copyright 2002-2008 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org
.argeo
.osgi
.boot
.internal
.springutil
;
19 import java
.util
.ArrayList
;
20 import java
.util
.Arrays
;
21 import java
.util
.Collection
;
22 import java
.util
.Collections
;
23 import java
.util
.Enumeration
;
24 import java
.util
.Iterator
;
25 import java
.util
.LinkedList
;
26 import java
.util
.List
;
27 import java
.util
.Locale
;
28 import java
.util
.Properties
;
30 import java
.util
.StringTokenizer
;
31 import java
.util
.TreeSet
;
34 * Miscellaneous {@link String} utility methods.
36 * <p>Mainly for internal use within the framework; consider
37 * <a href="http://jakarta.apache.org/commons/lang/">Jakarta's Commons Lang</a>
38 * for a more comprehensive suite of String utilities.
40 * <p>This class delivers some simple functionality that should really
41 * be provided by the core Java <code>String</code> and {@link StringBuffer}
42 * classes, such as the ability to {@link #replace} all occurrences of a given
43 * substring in a target string. It also provides easy-to-use methods to convert
44 * between delimited strings, such as CSV strings, and collections and arrays.
47 * @author Juergen Hoeller
48 * @author Keith Donald
51 * @since 16 April 2001
52 * @see org.apache.commons.lang.StringUtils
54 @SuppressWarnings({ "rawtypes", "unchecked" })
55 public abstract class StringUtils
{
57 private static final String FOLDER_SEPARATOR
= "/";
59 private static final String WINDOWS_FOLDER_SEPARATOR
= "\\";
61 private static final String TOP_PATH
= "..";
63 private static final String CURRENT_PATH
= ".";
65 private static final char EXTENSION_SEPARATOR
= '.';
68 //---------------------------------------------------------------------
69 // General convenience methods for working with Strings
70 //---------------------------------------------------------------------
73 * Check that the given CharSequence is neither <code>null</code> nor of length 0.
74 * Note: Will return <code>true</code> for a CharSequence that purely consists of whitespace.
76 * StringUtils.hasLength(null) = false
77 * StringUtils.hasLength("") = false
78 * StringUtils.hasLength(" ") = true
79 * StringUtils.hasLength("Hello") = true
81 * @param str the CharSequence to check (may be <code>null</code>)
82 * @return <code>true</code> if the CharSequence is not null and has length
83 * @see #hasText(String)
85 public static boolean hasLength(CharSequence str
) {
86 return (str
!= null && str
.length() > 0);
90 * Check that the given String is neither <code>null</code> nor of length 0.
91 * Note: Will return <code>true</code> for a String that purely consists of whitespace.
92 * @param str the String to check (may be <code>null</code>)
93 * @return <code>true</code> if the String is not null and has length
94 * @see #hasLength(CharSequence)
96 public static boolean hasLength(String str
) {
97 return hasLength((CharSequence
) str
);
101 * Check whether the given CharSequence has actual text.
102 * More specifically, returns <code>true</code> if the string not <code>null</code>,
103 * its length is greater than 0, and it contains at least one non-whitespace character.
105 * StringUtils.hasText(null) = false
106 * StringUtils.hasText("") = false
107 * StringUtils.hasText(" ") = false
108 * StringUtils.hasText("12345") = true
109 * StringUtils.hasText(" 12345 ") = true
111 * @param str the CharSequence to check (may be <code>null</code>)
112 * @return <code>true</code> if the CharSequence is not <code>null</code>,
113 * its length is greater than 0, and it does not contain whitespace only
114 * @see java.lang.Character#isWhitespace
116 public static boolean hasText(CharSequence str
) {
117 if (!hasLength(str
)) {
120 int strLen
= str
.length();
121 for (int i
= 0; i
< strLen
; i
++) {
122 if (!Character
.isWhitespace(str
.charAt(i
))) {
130 * Check whether the given String has actual text.
131 * More specifically, returns <code>true</code> if the string not <code>null</code>,
132 * its length is greater than 0, and it contains at least one non-whitespace character.
133 * @param str the String to check (may be <code>null</code>)
134 * @return <code>true</code> if the String is not <code>null</code>, its length is
135 * greater than 0, and it does not contain whitespace only
136 * @see #hasText(CharSequence)
138 public static boolean hasText(String str
) {
139 return hasText((CharSequence
) str
);
143 * Check whether the given CharSequence contains any whitespace characters.
144 * @param str the CharSequence to check (may be <code>null</code>)
145 * @return <code>true</code> if the CharSequence is not empty and
146 * contains at least 1 whitespace character
147 * @see java.lang.Character#isWhitespace
149 public static boolean containsWhitespace(CharSequence str
) {
150 if (!hasLength(str
)) {
153 int strLen
= str
.length();
154 for (int i
= 0; i
< strLen
; i
++) {
155 if (Character
.isWhitespace(str
.charAt(i
))) {
163 * Check whether the given String contains any whitespace characters.
164 * @param str the String to check (may be <code>null</code>)
165 * @return <code>true</code> if the String is not empty and
166 * contains at least 1 whitespace character
167 * @see #containsWhitespace(CharSequence)
169 public static boolean containsWhitespace(String str
) {
170 return containsWhitespace((CharSequence
) str
);
174 * Trim leading and trailing whitespace from the given String.
175 * @param str the String to check
176 * @return the trimmed String
177 * @see java.lang.Character#isWhitespace
179 public static String
trimWhitespace(String str
) {
180 if (!hasLength(str
)) {
183 StringBuffer buf
= new StringBuffer(str
);
184 while (buf
.length() > 0 && Character
.isWhitespace(buf
.charAt(0))) {
187 while (buf
.length() > 0 && Character
.isWhitespace(buf
.charAt(buf
.length() - 1))) {
188 buf
.deleteCharAt(buf
.length() - 1);
190 return buf
.toString();
194 * Trim <i>all</i> whitespace from the given String:
195 * leading, trailing, and inbetween characters.
196 * @param str the String to check
197 * @return the trimmed String
198 * @see java.lang.Character#isWhitespace
200 public static String
trimAllWhitespace(String str
) {
201 if (!hasLength(str
)) {
204 StringBuffer buf
= new StringBuffer(str
);
206 while (buf
.length() > index
) {
207 if (Character
.isWhitespace(buf
.charAt(index
))) {
208 buf
.deleteCharAt(index
);
214 return buf
.toString();
218 * Trim leading whitespace from the given String.
219 * @param str the String to check
220 * @return the trimmed String
221 * @see java.lang.Character#isWhitespace
223 public static String
trimLeadingWhitespace(String str
) {
224 if (!hasLength(str
)) {
227 StringBuffer buf
= new StringBuffer(str
);
228 while (buf
.length() > 0 && Character
.isWhitespace(buf
.charAt(0))) {
231 return buf
.toString();
235 * Trim trailing whitespace from the given String.
236 * @param str the String to check
237 * @return the trimmed String
238 * @see java.lang.Character#isWhitespace
240 public static String
trimTrailingWhitespace(String str
) {
241 if (!hasLength(str
)) {
244 StringBuffer buf
= new StringBuffer(str
);
245 while (buf
.length() > 0 && Character
.isWhitespace(buf
.charAt(buf
.length() - 1))) {
246 buf
.deleteCharAt(buf
.length() - 1);
248 return buf
.toString();
252 * Trim all occurences of the supplied leading character from the given String.
253 * @param str the String to check
254 * @param leadingCharacter the leading character to be trimmed
255 * @return the trimmed String
257 public static String
trimLeadingCharacter(String str
, char leadingCharacter
) {
258 if (!hasLength(str
)) {
261 StringBuffer buf
= new StringBuffer(str
);
262 while (buf
.length() > 0 && buf
.charAt(0) == leadingCharacter
) {
265 return buf
.toString();
269 * Trim all occurences of the supplied trailing character from the given String.
270 * @param str the String to check
271 * @param trailingCharacter the trailing character to be trimmed
272 * @return the trimmed String
274 public static String
trimTrailingCharacter(String str
, char trailingCharacter
) {
275 if (!hasLength(str
)) {
278 StringBuffer buf
= new StringBuffer(str
);
279 while (buf
.length() > 0 && buf
.charAt(buf
.length() - 1) == trailingCharacter
) {
280 buf
.deleteCharAt(buf
.length() - 1);
282 return buf
.toString();
287 * Test if the given String starts with the specified prefix,
288 * ignoring upper/lower case.
289 * @param str the String to check
290 * @param prefix the prefix to look for
291 * @see java.lang.String#startsWith
293 public static boolean startsWithIgnoreCase(String str
, String prefix
) {
294 if (str
== null || prefix
== null) {
297 if (str
.startsWith(prefix
)) {
300 if (str
.length() < prefix
.length()) {
303 String lcStr
= str
.substring(0, prefix
.length()).toLowerCase();
304 String lcPrefix
= prefix
.toLowerCase();
305 return lcStr
.equals(lcPrefix
);
309 * Test if the given String ends with the specified suffix,
310 * ignoring upper/lower case.
311 * @param str the String to check
312 * @param suffix the suffix to look for
313 * @see java.lang.String#endsWith
315 public static boolean endsWithIgnoreCase(String str
, String suffix
) {
316 if (str
== null || suffix
== null) {
319 if (str
.endsWith(suffix
)) {
322 if (str
.length() < suffix
.length()) {
326 String lcStr
= str
.substring(str
.length() - suffix
.length()).toLowerCase();
327 String lcSuffix
= suffix
.toLowerCase();
328 return lcStr
.equals(lcSuffix
);
332 * Test whether the given string matches the given substring
333 * at the given index.
334 * @param str the original string (or StringBuffer)
335 * @param index the index in the original string to start matching against
336 * @param substring the substring to match at the given index
338 public static boolean substringMatch(CharSequence str
, int index
, CharSequence substring
) {
339 for (int j
= 0; j
< substring
.length(); j
++) {
341 if (i
>= str
.length() || str
.charAt(i
) != substring
.charAt(j
)) {
349 * Count the occurrences of the substring in string s.
350 * @param str string to search in. Return 0 if this is null.
351 * @param sub string to search for. Return 0 if this is null.
353 public static int countOccurrencesOf(String str
, String sub
) {
354 if (str
== null || sub
== null || str
.length() == 0 || sub
.length() == 0) {
357 int count
= 0, pos
= 0, idx
= 0;
358 while ((idx
= str
.indexOf(sub
, pos
)) != -1) {
360 pos
= idx
+ sub
.length();
366 * Replace all occurences of a substring within a string with
368 * @param inString String to examine
369 * @param oldPattern String to replace
370 * @param newPattern String to insert
371 * @return a String with the replacements
373 public static String
replace(String inString
, String oldPattern
, String newPattern
) {
374 if (!hasLength(inString
) || !hasLength(oldPattern
) || newPattern
== null) {
377 StringBuffer sbuf
= new StringBuffer();
378 // output StringBuffer we'll build up
379 int pos
= 0; // our position in the old string
380 int index
= inString
.indexOf(oldPattern
);
381 // the index of an occurrence we've found, or -1
382 int patLen
= oldPattern
.length();
384 sbuf
.append(inString
.substring(pos
, index
));
385 sbuf
.append(newPattern
);
386 pos
= index
+ patLen
;
387 index
= inString
.indexOf(oldPattern
, pos
);
389 sbuf
.append(inString
.substring(pos
));
390 // remember to append any characters to the right of a match
391 return sbuf
.toString();
395 * Delete all occurrences of the given substring.
396 * @param inString the original String
397 * @param pattern the pattern to delete all occurrences of
398 * @return the resulting String
400 public static String
delete(String inString
, String pattern
) {
401 return replace(inString
, pattern
, "");
405 * Delete any character in a given String.
406 * @param inString the original String
407 * @param charsToDelete a set of characters to delete.
408 * E.g. "az\n" will delete 'a's, 'z's and new lines.
409 * @return the resulting String
411 public static String
deleteAny(String inString
, String charsToDelete
) {
412 if (!hasLength(inString
) || !hasLength(charsToDelete
)) {
415 StringBuffer out
= new StringBuffer();
416 for (int i
= 0; i
< inString
.length(); i
++) {
417 char c
= inString
.charAt(i
);
418 if (charsToDelete
.indexOf(c
) == -1) {
422 return out
.toString();
426 //---------------------------------------------------------------------
427 // Convenience methods for working with formatted Strings
428 //---------------------------------------------------------------------
431 * Quote the given String with single quotes.
432 * @param str the input String (e.g. "myString")
433 * @return the quoted String (e.g. "'myString'"),
434 * or <code>null<code> if the input was <code>null</code>
436 public static String
quote(String str
) {
437 return (str
!= null ?
"'" + str
+ "'" : null);
441 * Turn the given Object into a String with single quotes
442 * if it is a String; keeping the Object as-is else.
443 * @param obj the input Object (e.g. "myString")
444 * @return the quoted String (e.g. "'myString'"),
445 * or the input object as-is if not a String
447 public static Object
quoteIfString(Object obj
) {
448 return (obj
instanceof String ?
quote((String
) obj
) : obj
);
452 * Unqualify a string qualified by a '.' dot character. For example,
453 * "this.name.is.qualified", returns "qualified".
454 * @param qualifiedName the qualified name
456 public static String
unqualify(String qualifiedName
) {
457 return unqualify(qualifiedName
, '.');
461 * Unqualify a string qualified by a separator character. For example,
462 * "this:name:is:qualified" returns "qualified" if using a ':' separator.
463 * @param qualifiedName the qualified name
464 * @param separator the separator
466 public static String
unqualify(String qualifiedName
, char separator
) {
467 return qualifiedName
.substring(qualifiedName
.lastIndexOf(separator
) + 1);
471 * Capitalize a <code>String</code>, changing the first letter to
472 * upper case as per {@link Character#toUpperCase(char)}.
473 * No other letters are changed.
474 * @param str the String to capitalize, may be <code>null</code>
475 * @return the capitalized String, <code>null</code> if null
477 public static String
capitalize(String str
) {
478 return changeFirstCharacterCase(str
, true);
482 * Uncapitalize a <code>String</code>, changing the first letter to
483 * lower case as per {@link Character#toLowerCase(char)}.
484 * No other letters are changed.
485 * @param str the String to uncapitalize, may be <code>null</code>
486 * @return the uncapitalized String, <code>null</code> if null
488 public static String
uncapitalize(String str
) {
489 return changeFirstCharacterCase(str
, false);
492 private static String
changeFirstCharacterCase(String str
, boolean capitalize
) {
493 if (str
== null || str
.length() == 0) {
496 StringBuffer buf
= new StringBuffer(str
.length());
498 buf
.append(Character
.toUpperCase(str
.charAt(0)));
501 buf
.append(Character
.toLowerCase(str
.charAt(0)));
503 buf
.append(str
.substring(1));
504 return buf
.toString();
508 * Extract the filename from the given path,
509 * e.g. "mypath/myfile.txt" -> "myfile.txt".
510 * @param path the file path (may be <code>null</code>)
511 * @return the extracted filename, or <code>null</code> if none
513 public static String
getFilename(String path
) {
517 int separatorIndex
= path
.lastIndexOf(FOLDER_SEPARATOR
);
518 return (separatorIndex
!= -1 ? path
.substring(separatorIndex
+ 1) : path
);
522 * Extract the filename extension from the given path,
523 * e.g. "mypath/myfile.txt" -> "txt".
524 * @param path the file path (may be <code>null</code>)
525 * @return the extracted filename extension, or <code>null</code> if none
527 public static String
getFilenameExtension(String path
) {
531 int sepIndex
= path
.lastIndexOf(EXTENSION_SEPARATOR
);
532 return (sepIndex
!= -1 ? path
.substring(sepIndex
+ 1) : null);
536 * Strip the filename extension from the given path,
537 * e.g. "mypath/myfile.txt" -> "mypath/myfile".
538 * @param path the file path (may be <code>null</code>)
539 * @return the path with stripped filename extension,
540 * or <code>null</code> if none
542 public static String
stripFilenameExtension(String path
) {
546 int sepIndex
= path
.lastIndexOf(EXTENSION_SEPARATOR
);
547 return (sepIndex
!= -1 ? path
.substring(0, sepIndex
) : path
);
551 * Apply the given relative path to the given path,
552 * assuming standard Java folder separation (i.e. "/" separators);
553 * @param path the path to start from (usually a full file path)
554 * @param relativePath the relative path to apply
555 * (relative to the full file path above)
556 * @return the full file path that results from applying the relative path
558 public static String
applyRelativePath(String path
, String relativePath
) {
559 int separatorIndex
= path
.lastIndexOf(FOLDER_SEPARATOR
);
560 if (separatorIndex
!= -1) {
561 String newPath
= path
.substring(0, separatorIndex
);
562 if (!relativePath
.startsWith(FOLDER_SEPARATOR
)) {
563 newPath
+= FOLDER_SEPARATOR
;
565 return newPath
+ relativePath
;
573 * Normalize the path by suppressing sequences like "path/.." and
575 * <p>The result is convenient for path comparison. For other uses,
576 * notice that Windows separators ("\") are replaced by simple slashes.
577 * @param path the original path
578 * @return the normalized path
580 public static String
cleanPath(String path
) {
584 String pathToUse
= replace(path
, WINDOWS_FOLDER_SEPARATOR
, FOLDER_SEPARATOR
);
586 // Strip prefix from path to analyze, to not treat it as part of the
587 // first path element. This is necessary to correctly parse paths like
588 // "file:core/../core/io/Resource.class", where the ".." should just
589 // strip the first "core" directory while keeping the "file:" prefix.
590 int prefixIndex
= pathToUse
.indexOf(":");
592 if (prefixIndex
!= -1) {
593 prefix
= pathToUse
.substring(0, prefixIndex
+ 1);
594 pathToUse
= pathToUse
.substring(prefixIndex
+ 1);
596 if (pathToUse
.startsWith(FOLDER_SEPARATOR
)) {
597 prefix
= prefix
+ FOLDER_SEPARATOR
;
598 pathToUse
= pathToUse
.substring(1);
601 String
[] pathArray
= delimitedListToStringArray(pathToUse
, FOLDER_SEPARATOR
);
602 List pathElements
= new LinkedList();
605 for (int i
= pathArray
.length
- 1; i
>= 0; i
--) {
606 String element
= pathArray
[i
];
607 if (CURRENT_PATH
.equals(element
)) {
608 // Points to current directory - drop it.
610 else if (TOP_PATH
.equals(element
)) {
611 // Registering top path found.
616 // Merging path element with element corresponding to top path.
620 // Normal path element found.
621 pathElements
.add(0, element
);
626 // Remaining top paths need to be retained.
627 for (int i
= 0; i
< tops
; i
++) {
628 pathElements
.add(0, TOP_PATH
);
631 return prefix
+ collectionToDelimitedString(pathElements
, FOLDER_SEPARATOR
);
635 * Compare two paths after normalization of them.
636 * @param path1 first path for comparison
637 * @param path2 second path for comparison
638 * @return whether the two paths are equivalent after normalization
640 public static boolean pathEquals(String path1
, String path2
) {
641 return cleanPath(path1
).equals(cleanPath(path2
));
645 * Parse the given <code>localeString</code> into a {@link Locale}.
646 * <p>This is the inverse operation of {@link Locale#toString Locale's toString}.
647 * @param localeString the locale string, following <code>Locale's</code>
648 * <code>toString()</code> format ("en", "en_UK", etc);
649 * also accepts spaces as separators, as an alternative to underscores
650 * @return a corresponding <code>Locale</code> instance
652 public static Locale
parseLocaleString(String localeString
) {
653 String
[] parts
= tokenizeToStringArray(localeString
, "_ ", false, false);
654 String language
= (parts
.length
> 0 ? parts
[0] : "");
655 String country
= (parts
.length
> 1 ? parts
[1] : "");
657 if (parts
.length
>= 2) {
658 // There is definitely a variant, and it is everything after the country
659 // code sans the separator between the country code and the variant.
660 int endIndexOfCountryCode
= localeString
.indexOf(country
) + country
.length();
661 // Strip off any leading '_' and whitespace, what's left is the variant.
662 variant
= trimLeadingWhitespace(localeString
.substring(endIndexOfCountryCode
));
663 if (variant
.startsWith("_")) {
664 variant
= trimLeadingCharacter(variant
, '_');
667 return (language
.length() > 0 ?
new Locale(language
, country
, variant
) : null);
671 * Determine the RFC 3066 compliant language tag,
672 * as used for the HTTP "Accept-Language" header.
673 * @param locale the Locale to transform to a language tag
674 * @return the RFC 3066 compliant language tag as String
676 public static String
toLanguageTag(Locale locale
) {
677 return locale
.getLanguage() + (hasText(locale
.getCountry()) ?
"-" + locale
.getCountry() : "");
681 //---------------------------------------------------------------------
682 // Convenience methods for working with String arrays
683 //---------------------------------------------------------------------
686 * Append the given String to the given String array, returning a new array
687 * consisting of the input array contents plus the given String.
688 * @param array the array to append to (can be <code>null</code>)
689 * @param str the String to append
690 * @return the new array (never <code>null</code>)
692 public static String
[] addStringToArray(String
[] array
, String str
) {
693 if (ObjectUtils
.isEmpty(array
)) {
694 return new String
[] {str
};
696 String
[] newArr
= new String
[array
.length
+ 1];
697 System
.arraycopy(array
, 0, newArr
, 0, array
.length
);
698 newArr
[array
.length
] = str
;
703 * Concatenate the given String arrays into one,
704 * with overlapping array elements included twice.
705 * <p>The order of elements in the original arrays is preserved.
706 * @param array1 the first array (can be <code>null</code>)
707 * @param array2 the second array (can be <code>null</code>)
708 * @return the new array (<code>null</code> if both given arrays were <code>null</code>)
710 public static String
[] concatenateStringArrays(String
[] array1
, String
[] array2
) {
711 if (ObjectUtils
.isEmpty(array1
)) {
714 if (ObjectUtils
.isEmpty(array2
)) {
717 String
[] newArr
= new String
[array1
.length
+ array2
.length
];
718 System
.arraycopy(array1
, 0, newArr
, 0, array1
.length
);
719 System
.arraycopy(array2
, 0, newArr
, array1
.length
, array2
.length
);
724 * Merge the given String arrays into one, with overlapping
725 * array elements only included once.
726 * <p>The order of elements in the original arrays is preserved
727 * (with the exception of overlapping elements, which are only
728 * included on their first occurence).
729 * @param array1 the first array (can be <code>null</code>)
730 * @param array2 the second array (can be <code>null</code>)
731 * @return the new array (<code>null</code> if both given arrays were <code>null</code>)
733 public static String
[] mergeStringArrays(String
[] array1
, String
[] array2
) {
734 if (ObjectUtils
.isEmpty(array1
)) {
737 if (ObjectUtils
.isEmpty(array2
)) {
740 List result
= new ArrayList();
741 result
.addAll(Arrays
.asList(array1
));
742 for (int i
= 0; i
< array2
.length
; i
++) {
743 String str
= array2
[i
];
744 if (!result
.contains(str
)) {
748 return toStringArray(result
);
752 * Turn given source String array into sorted array.
753 * @param array the source array
754 * @return the sorted array (never <code>null</code>)
756 public static String
[] sortStringArray(String
[] array
) {
757 if (ObjectUtils
.isEmpty(array
)) {
758 return new String
[0];
765 * Copy the given Collection into a String array.
766 * The Collection must contain String elements only.
767 * @param collection the Collection to copy
768 * @return the String array (<code>null</code> if the passed-in
769 * Collection was <code>null</code>)
771 public static String
[] toStringArray(Collection collection
) {
772 if (collection
== null) {
775 return (String
[]) collection
.toArray(new String
[collection
.size()]);
779 * Copy the given Enumeration into a String array.
780 * The Enumeration must contain String elements only.
781 * @param enumeration the Enumeration to copy
782 * @return the String array (<code>null</code> if the passed-in
783 * Enumeration was <code>null</code>)
785 public static String
[] toStringArray(Enumeration enumeration
) {
786 if (enumeration
== null) {
789 List list
= Collections
.list(enumeration
);
790 return (String
[]) list
.toArray(new String
[list
.size()]);
794 * Trim the elements of the given String array,
795 * calling <code>String.trim()</code> on each of them.
796 * @param array the original String array
797 * @return the resulting array (of the same size) with trimmed elements
799 public static String
[] trimArrayElements(String
[] array
) {
800 if (ObjectUtils
.isEmpty(array
)) {
801 return new String
[0];
803 String
[] result
= new String
[array
.length
];
804 for (int i
= 0; i
< array
.length
; i
++) {
805 String element
= array
[i
];
806 result
[i
] = (element
!= null ? element
.trim() : null);
812 * Remove duplicate Strings from the given array.
813 * Also sorts the array, as it uses a TreeSet.
814 * @param array the String array
815 * @return an array without duplicates, in natural sort order
817 public static String
[] removeDuplicateStrings(String
[] array
) {
818 if (ObjectUtils
.isEmpty(array
)) {
821 Set set
= new TreeSet();
822 for (int i
= 0; i
< array
.length
; i
++) {
825 return toStringArray(set
);
829 * Split a String at the first occurrence of the delimiter.
830 * Does not include the delimiter in the result.
831 * @param toSplit the string to split
832 * @param delimiter to split the string up with
833 * @return a two element array with index 0 being before the delimiter, and
834 * index 1 being after the delimiter (neither element includes the delimiter);
835 * or <code>null</code> if the delimiter wasn't found in the given input String
837 public static String
[] split(String toSplit
, String delimiter
) {
838 if (!hasLength(toSplit
) || !hasLength(delimiter
)) {
841 int offset
= toSplit
.indexOf(delimiter
);
845 String beforeDelimiter
= toSplit
.substring(0, offset
);
846 String afterDelimiter
= toSplit
.substring(offset
+ delimiter
.length());
847 return new String
[] {beforeDelimiter
, afterDelimiter
};
851 * Take an array Strings and split each element based on the given delimiter.
852 * A <code>Properties</code> instance is then generated, with the left of the
853 * delimiter providing the key, and the right of the delimiter providing the value.
854 * <p>Will trim both the key and value before adding them to the
855 * <code>Properties</code> instance.
856 * @param array the array to process
857 * @param delimiter to split each element using (typically the equals symbol)
858 * @return a <code>Properties</code> instance representing the array contents,
859 * or <code>null</code> if the array to process was null or empty
861 public static Properties
splitArrayElementsIntoProperties(String
[] array
, String delimiter
) {
862 return splitArrayElementsIntoProperties(array
, delimiter
, null);
866 * Take an array Strings and split each element based on the given delimiter.
867 * A <code>Properties</code> instance is then generated, with the left of the
868 * delimiter providing the key, and the right of the delimiter providing the value.
869 * <p>Will trim both the key and value before adding them to the
870 * <code>Properties</code> instance.
871 * @param array the array to process
872 * @param delimiter to split each element using (typically the equals symbol)
873 * @param charsToDelete one or more characters to remove from each element
874 * prior to attempting the split operation (typically the quotation mark
875 * symbol), or <code>null</code> if no removal should occur
876 * @return a <code>Properties</code> instance representing the array contents,
877 * or <code>null</code> if the array to process was <code>null</code> or empty
879 public static Properties
splitArrayElementsIntoProperties(
880 String
[] array
, String delimiter
, String charsToDelete
) {
882 if (ObjectUtils
.isEmpty(array
)) {
885 Properties result
= new Properties();
886 for (int i
= 0; i
< array
.length
; i
++) {
887 String element
= array
[i
];
888 if (charsToDelete
!= null) {
889 element
= deleteAny(array
[i
], charsToDelete
);
891 String
[] splittedElement
= split(element
, delimiter
);
892 if (splittedElement
== null) {
895 result
.setProperty(splittedElement
[0].trim(), splittedElement
[1].trim());
901 * Tokenize the given String into a String array via a StringTokenizer.
902 * Trims tokens and omits empty tokens.
903 * <p>The given delimiters string is supposed to consist of any number of
904 * delimiter characters. Each of those characters can be used to separate
905 * tokens. A delimiter is always a single character; for multi-character
906 * delimiters, consider using <code>delimitedListToStringArray</code>
907 * @param str the String to tokenize
908 * @param delimiters the delimiter characters, assembled as String
909 * (each of those characters is individually considered as delimiter).
910 * @return an array of the tokens
911 * @see java.util.StringTokenizer
912 * @see java.lang.String#trim()
913 * @see #delimitedListToStringArray
915 public static String
[] tokenizeToStringArray(String str
, String delimiters
) {
916 return tokenizeToStringArray(str
, delimiters
, true, true);
920 * Tokenize the given String into a String array via a StringTokenizer.
921 * <p>The given delimiters string is supposed to consist of any number of
922 * delimiter characters. Each of those characters can be used to separate
923 * tokens. A delimiter is always a single character; for multi-character
924 * delimiters, consider using <code>delimitedListToStringArray</code>
925 * @param str the String to tokenize
926 * @param delimiters the delimiter characters, assembled as String
927 * (each of those characters is individually considered as delimiter)
928 * @param trimTokens trim the tokens via String's <code>trim</code>
929 * @param ignoreEmptyTokens omit empty tokens from the result array
930 * (only applies to tokens that are empty after trimming; StringTokenizer
931 * will not consider subsequent delimiters as token in the first place).
932 * @return an array of the tokens (<code>null</code> if the input String
933 * was <code>null</code>)
934 * @see java.util.StringTokenizer
935 * @see java.lang.String#trim()
936 * @see #delimitedListToStringArray
938 public static String
[] tokenizeToStringArray(
939 String str
, String delimiters
, boolean trimTokens
, boolean ignoreEmptyTokens
) {
944 StringTokenizer st
= new StringTokenizer(str
, delimiters
);
945 List tokens
= new ArrayList();
946 while (st
.hasMoreTokens()) {
947 String token
= st
.nextToken();
949 token
= token
.trim();
951 if (!ignoreEmptyTokens
|| token
.length() > 0) {
955 return toStringArray(tokens
);
959 * Take a String which is a delimited list and convert it to a String array.
960 * <p>A single delimiter can consists of more than one character: It will still
961 * be considered as single delimiter string, rather than as bunch of potential
962 * delimiter characters - in contrast to <code>tokenizeToStringArray</code>.
963 * @param str the input String
964 * @param delimiter the delimiter between elements (this is a single delimiter,
965 * rather than a bunch individual delimiter characters)
966 * @return an array of the tokens in the list
967 * @see #tokenizeToStringArray
969 public static String
[] delimitedListToStringArray(String str
, String delimiter
) {
970 return delimitedListToStringArray(str
, delimiter
, null);
974 * Take a String which is a delimited list and convert it to a String array.
975 * <p>A single delimiter can consists of more than one character: It will still
976 * be considered as single delimiter string, rather than as bunch of potential
977 * delimiter characters - in contrast to <code>tokenizeToStringArray</code>.
978 * @param str the input String
979 * @param delimiter the delimiter between elements (this is a single delimiter,
980 * rather than a bunch individual delimiter characters)
981 * @param charsToDelete a set of characters to delete. Useful for deleting unwanted
982 * line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String.
983 * @return an array of the tokens in the list
984 * @see #tokenizeToStringArray
986 public static String
[] delimitedListToStringArray(String str
, String delimiter
, String charsToDelete
) {
988 return new String
[0];
990 if (delimiter
== null) {
991 return new String
[] {str
};
993 List result
= new ArrayList();
994 if ("".equals(delimiter
)) {
995 for (int i
= 0; i
< str
.length(); i
++) {
996 result
.add(deleteAny(str
.substring(i
, i
+ 1), charsToDelete
));
1002 while ((delPos
= str
.indexOf(delimiter
, pos
)) != -1) {
1003 result
.add(deleteAny(str
.substring(pos
, delPos
), charsToDelete
));
1004 pos
= delPos
+ delimiter
.length();
1006 if (str
.length() > 0 && pos
<= str
.length()) {
1007 // Add rest of String, but not in case of empty input.
1008 result
.add(deleteAny(str
.substring(pos
), charsToDelete
));
1011 return toStringArray(result
);
1015 * Convert a CSV list into an array of Strings.
1016 * @param str the input String
1017 * @return an array of Strings, or the empty array in case of empty input
1019 public static String
[] commaDelimitedListToStringArray(String str
) {
1020 return delimitedListToStringArray(str
, ",");
1024 * Convenience method to convert a CSV string list to a set.
1025 * Note that this will suppress duplicates.
1026 * @param str the input String
1027 * @return a Set of String entries in the list
1029 public static Set
commaDelimitedListToSet(String str
) {
1030 Set set
= new TreeSet();
1031 String
[] tokens
= commaDelimitedListToStringArray(str
);
1032 for (int i
= 0; i
< tokens
.length
; i
++) {
1039 * Convenience method to return a Collection as a delimited (e.g. CSV)
1040 * String. E.g. useful for <code>toString()</code> implementations.
1041 * @param coll the Collection to display
1042 * @param delim the delimiter to use (probably a ",")
1043 * @param prefix the String to start each element with
1044 * @param suffix the String to end each element with
1045 * @return the delimited String
1047 public static String
collectionToDelimitedString(Collection coll
, String delim
, String prefix
, String suffix
) {
1048 if (CollectionUtils
.isEmpty(coll
)) {
1051 StringBuffer sb
= new StringBuffer();
1052 Iterator it
= coll
.iterator();
1053 while (it
.hasNext()) {
1054 sb
.append(prefix
).append(it
.next()).append(suffix
);
1059 return sb
.toString();
1063 * Convenience method to return a Collection as a delimited (e.g. CSV)
1064 * String. E.g. useful for <code>toString()</code> implementations.
1065 * @param coll the Collection to display
1066 * @param delim the delimiter to use (probably a ",")
1067 * @return the delimited String
1069 public static String
collectionToDelimitedString(Collection coll
, String delim
) {
1070 return collectionToDelimitedString(coll
, delim
, "", "");
1074 * Convenience method to return a Collection as a CSV String.
1075 * E.g. useful for <code>toString()</code> implementations.
1076 * @param coll the Collection to display
1077 * @return the delimited String
1079 public static String
collectionToCommaDelimitedString(Collection coll
) {
1080 return collectionToDelimitedString(coll
, ",");
1084 * Convenience method to return a String array as a delimited (e.g. CSV)
1085 * String. E.g. useful for <code>toString()</code> implementations.
1086 * @param arr the array to display
1087 * @param delim the delimiter to use (probably a ",")
1088 * @return the delimited String
1090 public static String
arrayToDelimitedString(Object
[] arr
, String delim
) {
1091 if (ObjectUtils
.isEmpty(arr
)) {
1094 StringBuffer sb
= new StringBuffer();
1095 for (int i
= 0; i
< arr
.length
; i
++) {
1101 return sb
.toString();
1105 * Convenience method to return a String array as a CSV String.
1106 * E.g. useful for <code>toString()</code> implementations.
1107 * @param arr the array to display
1108 * @return the delimited String
1110 public static String
arrayToCommaDelimitedString(Object
[] arr
) {
1111 return arrayToDelimitedString(arr
, ",");