Top Description Fields Constructors Methods
org.springframework.util

public abstract Class StringUtils

extends Object
Class Inheritance
Imports
java.io.ByteArrayOutputStream, java.nio.charset.Charset, java.util.ArrayDeque, .ArrayList, .Arrays, .Collection, .Collections, .Deque, .Enumeration, .Iterator, .LinkedHashSet, .List, .Locale, .Properties, .Set, .StringJoiner, .StringTokenizer, .TimeZone, java.util.stream.Collectors, org.springframework.lang.Nullable

Miscellaneous String utility methods.

Mainly for internal use within the framework; consider Apache's Commons Lang for a more comprehensive suite of String utilities.

This class delivers some simple functionality that should really be provided by the core Java String and StringBuilder classes. It also provides easy-to-use methods to convert between delimited strings, such as CSV strings, and collections and arrays.

Authors
Rod Johnson, Juergen Hoeller, Keith Donald, Rob Harrop, Rick Evans, Arjen Poutsma, Sam Brannen, Brian Clozel
Since
16 April 2001

Field Summary

Modifier and TypeField and Description
private static final String
private static final int
private static final String[]
private static final char
private static final String
private static final char
private static final String
private static final String
private static final String

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public static String[]

Returns:

the new array (never null)
addStringToArray
(String[]
the array to append to (can be null)
array
,
String
the String to append
str
)

Append the given String to the given String array, returning a new array consisting of the input array contents plus the given String.

public static String

Returns:

the full file path that results from applying the relative path
applyRelativePath
(String
the path to start from (usually a full file path)
path
,
String
the relative path to apply (relative to the full file path above)
relativePath
)

Apply the given relative path to the given Java resource path, assuming standard Java folder separation (i.e. "/" separators).

public static String

Returns:

the delimited String
arrayToCommaDelimitedString
(Object[]
the array to display (potentially null or empty)
arr
)

Convert a String array into a comma delimited String (i.e., CSV).

public static String

Returns:

the delimited String
arrayToDelimitedString
(Object[]
the array to display (potentially null or empty)
arr
,
String
the delimiter to use (typically a ",")
delim
)

Convert a String array into a delimited String (e.g. CSV).

public static String

Returns:

the capitalized String
capitalize
(String
the String to capitalize
str
)

Capitalize a String, changing the first letter to upper case as per Character#toUpperCase(char).

private static String
changeFirstCharacterCase(String str, boolean capitalize)

public static String

Returns:

the normalized path
cleanPath
(String
the original path
path
)

Normalize the path by suppressing sequences like "path/.." and inner simple dots.

public static String

Returns:

the delimited String
collectionToCommaDelimitedString
(Collection<?>
the Collection to convert (potentially null or empty)
coll
)

Convert a Collection into a delimited String (e.g., CSV).

public static String

Returns:

the delimited String
collectionToDelimitedString
(Collection<?>
the Collection to convert (potentially null or empty)
coll
,
String
the delimiter to use (typically a ",")
delim
,
String
the String to start each element with
prefix
,
String
the String to end each element with
suffix
)

Convert a Collection to a delimited String (e.g. CSV).

public static String

Returns:

the delimited String
collectionToDelimitedString
(Collection<?>
the Collection to convert (potentially null or empty)
coll
,
String
the delimiter to use (typically a ",")
delim
)

Convert a Collection into a delimited String (e.g. CSV).

public static Set<String>

Returns:

a set of String entries in the list
commaDelimitedListToSet
(String
the input String (potentially null or empty)
str
)

Convert a comma delimited list (e.g., a row from a CSV file) into a set.

public static String[]

Returns:

an array of strings, or the empty array in case of empty input
commaDelimitedListToStringArray
(String
the input String (potentially null or empty)
str
)

Convert a comma delimited list (e.g., a row from a CSV file) into an array of strings.

public static String[]

Returns:

the new array (null if both given arrays were null)
concatenateStringArrays
(String[]
the first array (can be null)
array1
,
String[]
the second array (can be null)
array2
)

Concatenate the given String arrays into one, with overlapping array elements included twice.

public static boolean

Returns:

true if the CharSequence is not empty and contains at least 1 whitespace character
containsWhitespace
(CharSequence
the CharSequence to check (may be null)
str
)

Check whether the given CharSequence contains any whitespace characters.

public static boolean

Returns:

true if the String is not empty and contains at least 1 whitespace character
containsWhitespace
(String
the String to check (may be null)
str
)

Check whether the given String contains any whitespace characters.

public static int
countOccurrencesOf(String
string to search in
str
,
String
string to search for
sub
)

Count the occurrences of the substring sub in string str.

public static String

Returns:

the resulting String
delete
(String
the original String
inString
,
String
the pattern to delete all occurrences of
pattern
)

Delete all occurrences of the given substring.

public static String

Returns:

the resulting String
deleteAny
(String
the original String
inString
,
String
a set of characters to delete. E.g. "az\n" will delete 'a's, 'z's and new lines.
charsToDelete
)

Delete any character in a given String.

public static String[]

Returns:

an array of the tokens in the list
delimitedListToStringArray
(String
the input String (potentially null or empty)
str
,
String
the delimiter between elements (this is a single delimiter, rather than a bunch individual delimiter characters)
delimiter
)

Take a String that is a delimited list and convert it into a String array.

public static String[]

Returns:

an array of the tokens in the list
delimitedListToStringArray
(String
the input String (potentially null or empty)
str
,
String
the delimiter between elements (this is a single delimiter, rather than a bunch individual delimiter characters)
delimiter
,
String
a set of characters to delete; useful for deleting unwanted line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String
charsToDelete
)

Take a String that is a delimited list and convert it into a String array.

public static boolean
endsWithIgnoreCase(String
the String to check
str
,
String
the suffix to look for
suffix
)

Test if the given String ends with the specified suffix, ignoring upper/lower case.

public static String

Returns:

the extracted filename, or null if none
getFilename
(String
the file path (may be null)
path
)

Extract the filename from the given Java resource path, e.g. "mypath/myfile.txt" → "myfile.txt".

public static String

Returns:

the extracted filename extension, or null if none
getFilenameExtension
(String
the file path (may be null)
path
)

Extract the filename extension from the given Java resource path, e.g. "mypath/myfile.txt" → "txt".

public static boolean

Returns:

true if the CharSequence is not null and has length
hasLength
(CharSequence
the CharSequence to check (may be null)
str
)

Check that the given CharSequence is neither null nor of length 0.

public static boolean

Returns:

true if the String is not null and has length
hasLength
(String
the String to check (may be null)
str
)

Check that the given String is neither null nor of length 0.

public static boolean

Returns:

true if the CharSequence is not null, its length is greater than 0, and it does not contain whitespace only
hasText
(CharSequence
the CharSequence to check (may be null)
str
)

Check whether the given CharSequence contains actual text.

public static boolean

Returns:

true if the String is not null, its length is greater than 0, and it does not contain whitespace only
hasText
(String
the String to check (may be null)
str
)

Check whether the given String contains actual text.

public static boolean
isEmpty(Object
the candidate object (possibly a String)
str
)

Deprecated as of 5.3, in favor of hasLength(String) and hasText(String) (or ObjectUtils#isEmpty(Object))
Check whether the given object (possibly a String) is empty.
public static boolean
matchesCharacter(String
the String to check
str
,
char
the character to compare to
singleCharacter
)

Test if the given String matches the given single character.

public static Locale

Returns:

a corresponding Locale instance, or null if none
parseLocale
(String
the locale value: following either Locale's toString() format ("en", "en_UK", etc.), also accepting spaces as separators (as an alternative to underscores), or BCP 47 (e.g. "en-UK")
localeValue
)

Parse the given String value into a Locale, accepting the Locale#toString format as well as BCP 47 language tags as specified by Locale#forLanguageTag.

public static Locale

Returns:

a corresponding Locale instance, or null if none
parseLocaleString
(String
the locale String: following Locale's toString() format ("en", "en_UK", etc.), also accepting spaces as separators (as an alternative to underscores)
localeString
)

Parse the given String representation into a Locale.

public static TimeZone

Returns:

a corresponding TimeZone instance
parseTimeZoneString
(String
the time zone String, following TimeZone#getTimeZone(String) but throwing IllegalArgumentException in case of an invalid time zone specification
timeZoneString
)

Parse the given timeZoneString value into a TimeZone.

public static boolean

Returns:

whether the two paths are equivalent after normalization
pathEquals
(String
first path for comparison
path1
,
String
second path for comparison
path2
)

Compare two paths after normalization of them.

public static String

Returns:

the quoted String (e.g. "'myString'"), or null if the input was null
quote
(String
the input String (e.g. "myString")
str
)

Quote the given String with single quotes.

public static Object

Returns:

the quoted String (e.g. "'myString'"), or the input object as-is if not a String
quoteIfString
(Object
the input Object (e.g. "myString")
obj
)

Turn the given Object into a String with single quotes if it is a String; keeping the Object as-is else.

public static String[]

Returns:

an array without duplicates, in natural sort order
removeDuplicateStrings
(String[]
the String array (potentially empty)
array
)

Remove duplicate strings from the given array.

public static String

Returns:

a String with the replacements
replace
(String
String to examine
inString
,
String
String to replace
oldPattern
,
String
String to insert
newPattern
)

Replace all occurrences of a substring within a string with another string.

public static String[]

Returns:

the array in sorted form (never null)
sortStringArray
(String[]
the original array (potentially empty)
array
)

Sort the given String array if necessary.

public static String[]

Returns:

a two element array with index 0 being before the delimiter, and index 1 being after the delimiter (neither element includes the delimiter); or null if the delimiter wasn't found in the given input String
split
(String
the string to split (potentially null or empty)
toSplit
,
String
to split the string up with (potentially null or empty)
delimiter
)

Split a String at the first occurrence of the delimiter.

public static Properties

Returns:

a Properties instance representing the array contents, or null if the array to process was null or empty
splitArrayElementsIntoProperties
(String[]
the array to process
array
,
String
to split each element using (typically the equals symbol)
delimiter
)

Take an array of strings and split each element based on the given delimiter.

public static Properties

Returns:

a Properties instance representing the array contents, or null if the array to process was null or empty
splitArrayElementsIntoProperties
(String[]
the array to process
array
,
String
to split each element using (typically the equals symbol)
delimiter
,
String
one or more characters to remove from each element prior to attempting the split operation (typically the quotation mark symbol), or null if no removal should occur
charsToDelete
)

Take an array of strings and split each element based on the given delimiter.

public static boolean
startsWithIgnoreCase(String
the String to check
str
,
String
the prefix to look for
prefix
)

Test if the given String starts with the specified prefix, ignoring upper/lower case.

public static String

Returns:

the path with stripped filename extension
stripFilenameExtension
(String
the file path
path
)

Strip the filename extension from the given Java resource path, e.g. "mypath/myfile.txt" → "mypath/myfile".

public static boolean
substringMatch(CharSequence
the original string (or StringBuilder)
str
,
int
the index in the original string to start matching against
index
,
CharSequence
the substring to match at the given index
substring
)

Test whether the given string matches the given substring at the given index.

public static String[]

Returns:

an array of the tokens
tokenizeToStringArray
(String
the String to tokenize (potentially null or empty)
str
,
String
the delimiter characters, assembled as a String (each of the characters is individually considered as a delimiter)
delimiters
)

Tokenize the given String into a String array via a StringTokenizer.

public static String[]

Returns:

an array of the tokens
tokenizeToStringArray
(String
the String to tokenize (potentially null or empty)
str
,
String
the delimiter characters, assembled as a String (each of the characters is individually considered as a delimiter)
delimiters
,
boolean
trim the tokens via String#trim()
trimTokens
,
boolean
omit empty tokens from the result array (only applies to tokens that are empty after trimming; StringTokenizer will not consider subsequent delimiters as token in the first place).
ignoreEmptyTokens
)

Tokenize the given String into a String array via a StringTokenizer.

public static String[]

Returns:

the resulting String array
toStringArray
(Collection<String>
the Collection to copy (potentially null or empty)
collection
)

Copy the given Collection into a String array.

public static String[]

Returns:

the resulting String array
toStringArray
(Enumeration<String>
the Enumeration to copy (potentially null or empty)
enumeration
)

Copy the given Enumeration into a String array.

public static CharSequence

Returns:

the trimmed CharSequence
trimAllWhitespace
(CharSequence
the CharSequence to check
str
)

Trim all whitespace from the given CharSequence: leading, trailing, and in between characters.

public static String

Returns:

the trimmed String
trimAllWhitespace
(String
the String to check
str
)

Trim all whitespace from the given String: leading, trailing, and in between characters.

public static String[]

Returns:

the resulting array (of the same size) with trimmed elements
trimArrayElements
(String[]
the original String array (potentially empty)
array
)

Trim the elements of the given String array, calling String.trim() on each non-null element.

public static String

Returns:

the trimmed String
trimLeadingCharacter
(String
the String to check
str
,
char
the leading character to be trimmed
leadingCharacter
)

Trim all occurrences of the supplied leading character from the given String.

public static String

Returns:

the trimmed String
trimLeadingWhitespace
(String
the String to check
str
)

Deprecated since 6.0. since 6.0, in favor of String#stripLeading()
Trim leading whitespace from the given String.
public static String

Returns:

the trimmed String
trimTrailingCharacter
(String
the String to check
str
,
char
the trailing character to be trimmed
trailingCharacter
)

Trim all occurrences of the supplied trailing character from the given String.

public static String

Returns:

the trimmed String
trimTrailingWhitespace
(String
the String to check
str
)

Deprecated since 6.0. since 6.0, in favor of String#stripTrailing()
Trim trailing whitespace from the given String.
public static String

Returns:

the trimmed String
trimWhitespace
(String
the String to check
str
)

Deprecated since 6.0. since 6.0, in favor of String#strip()
Trim leading and trailing whitespace from the given String.
public static String

Returns:

a truncated string, or a string representation of the original CharSequence if its length does not exceed the threshold
truncate
(CharSequence
the CharSequence to truncate
charSequence
)

Truncate the supplied CharSequence.

public static String

Returns:

a truncated string, or a string representation of the original CharSequence if its length does not exceed the threshold
truncate
(CharSequence
the CharSequence to truncate
charSequence
,
int
the maximum length after which to truncate; must be a positive number
threshold
)

Truncate the supplied CharSequence.

public static String

Returns:

the uncapitalized String
uncapitalize
(String
the String to uncapitalize
str
)

Uncapitalize a String, changing the first letter to lower case as per Character#toLowerCase(char).

public static String

Returns:

the uncapitalized String
uncapitalizeAsProperty
(String
the String to uncapitalize
str
)

Uncapitalize a String in JavaBeans property format, changing the first letter to lower case as per Character#toLowerCase(char), unless the initial two letters are upper case in direct succession.

public static String
unqualify(String
the qualified name
qualifiedName
)

Unqualify a string qualified by a '.' dot character.

public static String
unqualify(String
the qualified name
qualifiedName
,
char
the separator
separator
)

Unqualify a string qualified by a separator character.

public static String

Returns:

the decoded value
uriDecode
(String
the encoded String
source
,
Charset
the character set
charset
)

Decode the given encoded URI component value.

private static void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait