Class StringUtils
Operations on String that are
null safe.
- IsEmpty/IsBlank - checks if a String contains text
- Trim/Strip - removes leading and trailing whitespace
- Equals/Compare - compares two strings null-safe
- startsWith - check if a String starts with a prefix null-safe
- endsWith - check if a String ends with a suffix null-safe
- IndexOf/LastIndexOf/Contains - null-safe index-of checks
- IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut - index-of any of a set of Strings
- ContainsOnly/ContainsNone/ContainsAny - does String contains only/none/any of these characters
- Substring/Left/Right/Mid - null-safe substring extractions
- SubstringBefore/SubstringAfter/SubstringBetween - substring extraction relative to other strings
- Split/Join - splits a String into an array of substrings and vice versa
- Remove/Delete - removes part of a String
- Replace/Overlay - Searches a String and replaces one String with another
- Chomp/Chop - removes the last part of a String
- AppendIfMissing - appends a suffix to the end of the String if not present
- PrependIfMissing - prepends a prefix to the start of the String if not present
- LeftPad/RightPad/Center/Repeat - pads a String
- UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - changes the case of a String
- CountMatches - counts the number of occurrences of one String in another
- IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable - checks the characters in a String
- DefaultString - protects against a null input String
- Rotate - rotate (circular shift) a String
- Reverse/ReverseDelimited - reverses a String
- Abbreviate - abbreviates a string using ellipsis or another given String
- Difference - compares Strings and reports on their differences
- LevenshteinDistance - the number of changes needed to change one String into another
The StringUtils class defines certain words related to
String handling.
- null -
null - empty - a zero-length string (
"") - space - the space character (
' ', char 32) - whitespace - the characters defined by
Character.isWhitespace(char) - trim - the characters <= 32 as in
String.trim()
StringUtils handles null input Strings quietly.
That is to say that a null input will return null.
Where a boolean or int is being returned
details vary by method.
A side effect of the null handling is that a
NullPointerException should be considered a bug in
StringUtils.
This class's source was modified from the Apache commons-lang library: https://github.com/apache/commons-lang/
#ThreadSafe#
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic Stringcapitalize(String str) Capitalizes a String changing the first character to title case as perCharacter.toTitleCase(int).static booleanCompares two Strings, returningtrueif they represent equal sequences of characters.static CharacterfindFirstOccurrence(String s, char... charsToMatch) Searches a string for the first occurrence of a character specified by a list of characters.static StringEncode the given bytes as a string using the given charsetstatic booleanisBlank(CharSequence cs) Checks if a CharSequence is empty (""), null or whitespace only.static booleanisEmpty(CharSequence cs) Checks if a CharSequence is empty ("") or null.static booleanChecks if a CharSequence is not empty (""), not null and not whitespace only.static StringConverts a String to lower case as perString.toLowerCase().static StringReturns a string whose value is the concatenation of this string repeatedcounttimes.static StringReplaces a String with another String inside a larger String, for the firstmaxvalues of the search String, case sensitively/insensitively based onignoreCasevalue.static StringreplaceEach(String text, String[] searchList, String[] replacementList) Replaces all occurrences of Strings within another String.static StringreplaceOnce(String text, String searchString, String replacement) Replaces a String with another String inside a larger String, once.static StringreplacePrefixIgnoreCase(String str, String prefix, String replacement) Replace the prefix of the string provided ignoring case considerations.static booleansafeStringToBoolean(String value) Convert a string to boolean safely (as opposed to the less strictBoolean.parseBoolean(String)).static booleanstartsWithIgnoreCase(String str, String prefix) Tests if this string starts with the specified prefix ignoring case considerations.static StringGets a substring from the specified String avoiding exceptions.static StringGets a substring from the specified String avoiding exceptions.static StringRemoves control characters (char <= 32) from both ends of this String, handlingnullby returningnull.static StringtrimToEmpty(String str) Removes control characters (char <= 32) from both ends of this String returning an empty String ("") if the String is empty ("") after the trim or if it isnull.static StringtrimToNull(String str) Removes control characters (char <= 32) from both ends of this String returningnullif the String is empty ("") after the trim or if it isnull.static Stringuncapitalize(String str) Uncapitalizes a String, changing the first character to lower case as perCharacter.toLowerCase(int).static StringConverts a String to upper case as perString.toUpperCase().
-
Method Details
-
isEmpty
Checks if a CharSequence is empty ("") or null.
StringUtils.isEmpty(null) = true StringUtils.isEmpty("") = true StringUtils.isEmpty(" ") = false StringUtils.isEmpty("bob") = false StringUtils.isEmpty(" bob ") = falseNOTE: This method changed in Lang version 2.0. It no longer trims the CharSequence. That functionality is available in isBlank().
- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif the CharSequence is empty or null- Since:
- 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
-
isBlank
Checks if a CharSequence is empty (""), null or whitespace only.
Whitespace is defined by
Character.isWhitespace(char).StringUtils.isBlank(null) = true StringUtils.isBlank("") = true StringUtils.isBlank(" ") = true StringUtils.isBlank("bob") = false StringUtils.isBlank(" bob ") = false- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif the CharSequence is null, empty or whitespace only- Since:
- 2.0, 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
-
isNotBlank
Checks if a CharSequence is not empty (""), not null and not whitespace only.
Whitespace is defined by
Character.isWhitespace(char).StringUtils.isNotBlank(null) = false StringUtils.isNotBlank("") = false StringUtils.isNotBlank(" ") = false StringUtils.isNotBlank("bob") = true StringUtils.isNotBlank(" bob ") = true- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif the CharSequence is not empty and not null and not whitespace only- Since:
- 2.0, 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence)
-
trim
Removes control characters (char <= 32) from both ends of this String, handling
nullby returningnull.The String is trimmed using
String.trim(). Trim removes start and end characters <= 32.StringUtils.trim(null) = null StringUtils.trim("") = "" StringUtils.trim(" ") = "" StringUtils.trim("abc") = "abc" StringUtils.trim(" abc ") = "abc"- Parameters:
str- the String to be trimmed, may be null- Returns:
- the trimmed string,
nullif null String input
-
trimToNull
Removes control characters (char <= 32) from both ends of this String returning
nullif the String is empty ("") after the trim or if it isnull.The String is trimmed using
String.trim(). Trim removes start and end characters <= 32.StringUtils.trimToNull(null) = null StringUtils.trimToNull("") = null StringUtils.trimToNull(" ") = null StringUtils.trimToNull("abc") = "abc" StringUtils.trimToNull(" abc ") = "abc"- Parameters:
str- the String to be trimmed, may be null- Returns:
- the trimmed String,
nullif only chars <= 32, empty or null String input - Since:
- 2.0
-
trimToEmpty
Removes control characters (char <= 32) from both ends of this String returning an empty String ("") if the String is empty ("") after the trim or if it is
null.The String is trimmed using
String.trim(). Trim removes start and end characters <= 32.StringUtils.trimToEmpty(null) = "" StringUtils.trimToEmpty("") = "" StringUtils.trimToEmpty(" ") = "" StringUtils.trimToEmpty("abc") = "abc" StringUtils.trimToEmpty(" abc ") = "abc"- Parameters:
str- the String to be trimmed, may be null- Returns:
- the trimmed String, or an empty String if
nullinput - Since:
- 2.0
-
equals
Compares two Strings, returning
trueif they represent equal sequences of characters.nulls are handled without exceptions. Twonullreferences are considered to be equal. The comparison is case sensitive.StringUtils.equals(null, null) = true StringUtils.equals(null, "abc") = false StringUtils.equals("abc", null) = false StringUtils.equals("abc", "abc") = true StringUtils.equals("abc", "ABC") = false- Parameters:
cs1- the first String, may benullcs2- the second String, may benull- Returns:
trueif the Strings are equal (case-sensitive), or bothnull- See Also:
-
substring
Gets a substring from the specified String avoiding exceptions.
A negative start position can be used to start
ncharacters from the end of the String.A
nullString will returnnull. An empty ("") String will return "".StringUtils.substring(null, *) = null StringUtils.substring("", *) = "" StringUtils.substring("abc", 0) = "abc" StringUtils.substring("abc", 2) = "c" StringUtils.substring("abc", 4) = "" StringUtils.substring("abc", -2) = "bc" StringUtils.substring("abc", -4) = "abc"- Parameters:
str- the String to get the substring from, may be nullstart- the position to start from, negative means count back from the end of the String by this many characters- Returns:
- substring from start position,
nullif null String input
-
substring
Gets a substring from the specified String avoiding exceptions.
A negative start position can be used to start/end
ncharacters from the end of the String.The returned substring starts with the character in the
startposition and ends before theendposition. All position counting is zero-based -- i.e., to start at the beginning of the string usestart = 0. Negative start and end positions can be used to specify offsets relative to the end of the String.If
startis not strictly to the left ofend, "" is returned.StringUtils.substring(null, *, *) = null StringUtils.substring("", * , *) = ""; StringUtils.substring("abc", 0, 2) = "ab" StringUtils.substring("abc", 2, 0) = "" StringUtils.substring("abc", 2, 4) = "c" StringUtils.substring("abc", 4, 6) = "" StringUtils.substring("abc", 2, 2) = "" StringUtils.substring("abc", -2, -1) = "b" StringUtils.substring("abc", -4, 2) = "ab"- Parameters:
str- the String to get the substring from, may be nullstart- the position to start from, negative means count back from the end of the String by this many charactersend- the position to end at (exclusive), negative means count back from the end of the String by this many characters- Returns:
- substring from start position to end position,
nullif null String input
-
upperCase
Converts a String to upper case as per
String.toUpperCase().A
nullinput String returnsnull.StringUtils.upperCase(null) = null StringUtils.upperCase("") = "" StringUtils.upperCase("aBc") = "ABC"This uses "ENGLISH" as the locale.
- Parameters:
str- the String to upper case, may be null- Returns:
- the upper cased String,
nullif null String input
-
lowerCase
Converts a String to lower case as per
String.toLowerCase().A
nullinput String returnsnull.StringUtils.lowerCase(null) = null StringUtils.lowerCase("") = "" StringUtils.lowerCase("aBc") = "abc"This uses "ENGLISH" as the locale.
- Parameters:
str- the String to lower case, may be null- Returns:
- the lower cased String,
nullif null String input
-
capitalize
Capitalizes a String changing the first character to title case as per
Character.toTitleCase(int). No other characters are changed.StringUtils.capitalize(null) = null StringUtils.capitalize("") = "" StringUtils.capitalize("cat") = "Cat" StringUtils.capitalize("cAt") = "CAt" StringUtils.capitalize("'cat'") = "'cat'"- Parameters:
str- the String to capitalize, may be null- Returns:
- the capitalized String,
nullif null String input - Since:
- 2.0
- See Also:
-
uncapitalize
Uncapitalizes a String, changing the first character to lower case as per
Character.toLowerCase(int). No other characters are changed.StringUtils.uncapitalize(null) = null StringUtils.uncapitalize("") = "" StringUtils.uncapitalize("cat") = "cat" StringUtils.uncapitalize("Cat") = "cat" StringUtils.uncapitalize("CAT") = "cAT"- Parameters:
str- the String to uncapitalize, may be null- Returns:
- the uncapitalized String,
nullif null String input - Since:
- 2.0
- See Also:
-
fromBytes
Encode the given bytes as a string using the given charset- Throws:
UncheckedIOException- with aCharacterCodingExceptionas the cause if the bytes cannot be encoded using the provided charset.
-
startsWithIgnoreCase
-
replaceOnce
Replaces a String with another String inside a larger String, once.
A
nullreference passed to this method is a no-op.StringUtils.replaceOnce(null, *, *) = null StringUtils.replaceOnce("", *, *) = "" StringUtils.replaceOnce("any", null, *) = "any" StringUtils.replaceOnce("any", *, null) = "any" StringUtils.replaceOnce("any", "", *) = "any" StringUtils.replaceOnce("aba", "a", null) = "aba" StringUtils.replaceOnce("aba", "a", "") = "ba" StringUtils.replaceOnce("aba", "a", "z") = "zba"- Parameters:
text- text to search and replace in, may be nullsearchString- the String to search for, may be nullreplacement- the String to replace with, may be null- Returns:
- the text with any replacements processed,
nullif null String input - See Also:
-
replace
Replaces a String with another String inside a larger String, for the first
maxvalues of the search String, case sensitively/insensitively based onignoreCasevalue.A
nullreference passed to this method is a no-op.StringUtils.replace(null, *, *, *, false) = null StringUtils.replace("", *, *, *, false) = "" StringUtils.replace("any", null, *, *, false) = "any" StringUtils.replace("any", *, null, *, false) = "any" StringUtils.replace("any", "", *, *, false) = "any" StringUtils.replace("any", *, *, 0, false) = "any" StringUtils.replace("abaa", "a", null, -1, false) = "abaa" StringUtils.replace("abaa", "a", "", -1, false) = "b" StringUtils.replace("abaa", "a", "z", 0, false) = "abaa" StringUtils.replace("abaa", "A", "z", 1, false) = "abaa" StringUtils.replace("abaa", "A", "z", 1, true) = "zbaa" StringUtils.replace("abAa", "a", "z", 2, true) = "zbza" StringUtils.replace("abAa", "a", "z", -1, true) = "zbzz"- Parameters:
text- text to search and replace in, may be nullsearchString- the String to search for (case insensitive), may be nullreplacement- the String to replace it with, may be null- Returns:
- the text with any replacements processed,
nullif null String input
-
replaceEach
Replaces all occurrences of Strings within another String.
A
nullreference passed to this method is a no-op, or if any "search string" or "string to replace" is null, that replace will be ignored. This will not repeat. For repeating replaces, call the overloaded method.StringUtils.replaceEach(null, *, *) = null StringUtils.replaceEach("", *, *) = "" StringUtils.replaceEach("aba", null, null) = "aba" StringUtils.replaceEach("aba", new String[0], null) = "aba" StringUtils.replaceEach("aba", null, new String[0]) = "aba" StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba" StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b" StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba" StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte" (example of how it does not repeat) StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"- Parameters:
text- text to search and replace in, no-op if nullsearchList- the Strings to search for, no-op if nullreplacementList- the Strings to replace them with, no-op if null- Returns:
- the text with any replacements processed,
nullif null String input - Throws:
IllegalArgumentException- if the lengths of the arrays are not the same (null is ok, and/or size 0)- Since:
- 2.4
-
replacePrefixIgnoreCase
Replace the prefix of the string provided ignoring case considerations.The unmatched part is unchanged.
- Parameters:
str- the string to replaceprefix- the prefix to findreplacement- the replacement- Returns:
- the replaced string
-
findFirstOccurrence
Searches a string for the first occurrence of a character specified by a list of characters.- Parameters:
s- The string to search.charsToMatch- A list of characters to search the string for.- Returns:
- The character that was first matched in the string or null if none of the characters were found.
-
safeStringToBoolean
Convert a string to boolean safely (as opposed to the less strictBoolean.parseBoolean(String)). If a customer specifies a boolean value it should be "true" or "false" (case insensitive) or an exception will be thrown. -
repeat
Returns a string whose value is the concatenation of this string repeatedcounttimes.If this string is empty or count is zero then the empty string is returned.
Logical clone of JDK11's
.invalid reference
String#repeat(int)- Parameters:
value- the string to repeatcount- number of times to repeat- Returns:
- A string composed of this string repeated
counttimes or the empty string if this string is empty or count is zero - Throws:
IllegalArgumentException- if thecountis negative.
-