Class StringUtil
- java.lang.Object
-
- org.apache.commons.lang3.StringUtils
-
- org.silverpeas.core.util.StringUtil
-
public class StringUtil extends org.apache.commons.lang3.StringUtils
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static String
abbreviate(String str, int offset, int maxWidth)
Abbreviates a String using ellipses.static boolean
areStringEquals(String s1, String s2)
Indicates if two Strings are equals, managing null.static String
asBase64(byte[] binaryData)
Encodes the specified binary data into a text of Base64 characters.static float
asFloat(String value)
static int
asInt(String value, int defaultValue)
static String
capitalize(String str)
Capitalizes a String changing the first character to title case as perCharacter.toTitleCase(int)
.static String
convertToEncoding(String toConvert, String encoding)
static int
countMatches(String str, String subStr)
Counts how many times the substring appears in the larger string.static String
defaultStringIfNotDefined(String string)
Returns either the passed in String, or if the String isnot defined
, an empty String ("").static String
defaultStringIfNotDefined(String string, String defaultString)
Returns either the passed in String, or if the String isnot defined
, the value ofdefaultString
.static String
doubleAntiSlash(String path)
Doubles the anti-slash character in a path value.static String
emptyString()
static String
escapeQuote(String text)
static String
format(String label, Map<String,?> values)
Format a string by extending the principle of the the method format() of the class java.text.MessageFormat to string arguments.static byte[]
fromBase64(String base64Text)
Decodes the specified text with Base64 characters in binary.static boolean
getBooleanValue(String expression)
Evaluate the expression and return true if expression equals "true", "yes", "y", "1" or "oui".static boolean
isDefined(String parameter)
static boolean
isFloat(String value)
static boolean
isInteger(String value)
static boolean
isLong(String value)
static boolean
isNotDefined(String parameter)
static boolean
isValidEmailAddress(String aEmailAddress)
Validate the form of an email address.static boolean
isValidHour(String time)
static String
join(Object[] array, char separator)
Joins the elements of the provided array into a single String containing the provided list of elements.static boolean
like(String actualValue, String expectedValue)
static boolean
likeIgnoreCase(String actualValue, String expectedValue)
static String
normalize(String string)
Normalizes the given string (which must be encoded into UTF-8) in order that the result contains only unified chars.static String
normalizeByRemovingAccent(String string)
Same treatment as the one ofnormalize(String)
but removes also the accented characters.static String
regexReplace(String source, String regex, String replacement)
Replace parts of a text by an one replacement string.static void
requireDefined(String name)
static String
requireDefined(String object, String message)
static String[]
split(String str, char separatorChar)
Splits the provided text into an array, separator specified.static String[]
split(String str, String separatorChars)
Splits the provided text into an array, separators specified.static String[]
splitByWholeSeparator(String str, String separator)
Splits the provided text into an array, separator string specified.static Iterable<String>
splitString(String str)
Splits the provided text into an array, using whitespace as the separator.static Iterable<String>
splitString(String str, char separatorChar)
Splits the provided text into an array, separator specified.static boolean
startsWith(CharSequence str, CharSequence prefix)
Check if a CharSequence starts with a specified prefix.static boolean
startsWithIgnoreCase(String str, String prefix)
Case insensitive check if a CharSequence starts with a specified prefix.static String
toAcceptableFilename(String name)
Replacesstatic String
truncate(String text, int maxLength)
static String
uncapitalize(String str)
Uncapitalizes a String, changing the first character to lower case as perCharacter.toLowerCase(int)
.-
Methods inherited from class org.apache.commons.lang3.StringUtils
abbreviate, abbreviate, abbreviate, abbreviateMiddle, appendIfMissing, appendIfMissingIgnoreCase, center, center, center, chomp, chomp, chop, compare, compare, compareIgnoreCase, compareIgnoreCase, contains, contains, containsAny, containsAny, containsAny, containsAnyIgnoreCase, containsIgnoreCase, containsNone, containsNone, containsOnly, containsOnly, containsWhitespace, countMatches, countMatches, defaultIfBlank, defaultIfEmpty, defaultString, defaultString, deleteWhitespace, difference, endsWith, endsWithAny, endsWithIgnoreCase, equals, equalsAny, equalsAnyIgnoreCase, equalsIgnoreCase, firstNonBlank, firstNonEmpty, getBytes, getBytes, getCommonPrefix, getDigits, getFuzzyDistance, getIfBlank, getIfEmpty, getJaroWinklerDistance, getLevenshteinDistance, getLevenshteinDistance, indexOf, indexOf, indexOf, indexOf, indexOfAny, indexOfAny, indexOfAny, indexOfAnyBut, indexOfAnyBut, indexOfDifference, indexOfDifference, indexOfIgnoreCase, indexOfIgnoreCase, isAllBlank, isAllEmpty, isAllLowerCase, isAllUpperCase, isAlpha, isAlphanumeric, isAlphanumericSpace, isAlphaSpace, isAnyBlank, isAnyEmpty, isAsciiPrintable, isBlank, isEmpty, isMixedCase, isNoneBlank, isNoneEmpty, isNotBlank, isNotEmpty, isNumeric, isNumericSpace, isWhitespace, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, join, joinWith, lastIndexOf, lastIndexOf, lastIndexOf, lastIndexOf, lastIndexOfAny, lastIndexOfIgnoreCase, lastIndexOfIgnoreCase, lastOrdinalIndexOf, left, leftPad, leftPad, leftPad, length, lowerCase, lowerCase, mid, normalizeSpace, ordinalIndexOf, overlay, prependIfMissing, prependIfMissingIgnoreCase, remove, remove, removeAll, removeEnd, removeEndIgnoreCase, removeFirst, removeIgnoreCase, removePattern, removeStart, removeStartIgnoreCase, repeat, repeat, repeat, replace, replace, replaceAll, replaceChars, replaceChars, replaceEach, replaceEachRepeatedly, replaceFirst, replaceIgnoreCase, replaceIgnoreCase, replaceOnce, replaceOnceIgnoreCase, replacePattern, reverse, reverseDelimited, right, rightPad, rightPad, rightPad, rotate, split, split, splitByCharacterType, splitByCharacterTypeCamelCase, splitByWholeSeparator, splitByWholeSeparatorPreserveAllTokens, splitByWholeSeparatorPreserveAllTokens, splitPreserveAllTokens, splitPreserveAllTokens, splitPreserveAllTokens, splitPreserveAllTokens, startsWithAny, startsWithIgnoreCase, strip, strip, stripAccents, stripAll, stripAll, stripEnd, stripStart, stripToEmpty, stripToNull, substring, substring, substringAfter, substringAfter, substringAfterLast, substringAfterLast, substringBefore, substringBefore, substringBeforeLast, substringBetween, substringBetween, substringsBetween, swapCase, toCodePoints, toEncodedString, toRootLowerCase, toRootUpperCase, toString, trim, trimToEmpty, trimToNull, truncate, unwrap, unwrap, upperCase, upperCase, valueOf, wrap, wrap, wrapIfMissing, wrapIfMissing
-
-
-
-
Field Detail
-
EMPTY
public static final String EMPTY
- See Also:
- Constant Field Values
-
NEWLINE
public static final String NEWLINE
-
-
Method Detail
-
emptyString
public static String emptyString()
-
startsWithIgnoreCase
public static boolean startsWithIgnoreCase(String str, String prefix)
Case insensitive check if a CharSequence starts with a specified prefix.
null
s are handled without exceptions. Twonull
references are considered to be equal. The comparison is case insensitive.StringUtils.startsWithIgnoreCase(null, null) = true StringUtils.startsWithIgnoreCase(null, "abc") = false StringUtils.startsWithIgnoreCase("abcdef", null) = false StringUtils.startsWithIgnoreCase("abcdef", "abc") = true StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
- Parameters:
str
- the text to check, may be nullprefix
- the text to find, may be null- Returns:
true
if the CharSequence starts with the prefix, case-insensitive, or bothnull
- See Also:
String.startsWith(String)
-
join
public static String join(Object[] array, char separator)
Joins the elements of the provided array into a single String containing the provided list of elements.
No delimiter is added before or after the list. Null objects or empty strings within the array are represented by empty strings.
StringUtils.join(null, *) = null StringUtils.join([], *) = "" StringUtils.join([null], *) = "" StringUtils.join(["a", "b", "c"], ';') = "a;b;c" StringUtils.join(["a", "b", "c"], null) = "abc" StringUtils.join([null, "", "a"], ';') = ";;a"
- Parameters:
array
- the array of values to join together, may be nullseparator
- the separator character to use- Returns:
- the joined String,
null
if null array input - Since:
- 2.0
-
abbreviate
public static String abbreviate(String str, int offset, int maxWidth)
Abbreviates a String using ellipses. This will turn "Now is the time for all good men" into "...is the time for..."
Works like
abbreviate(String, int)
, but allows you to specify a "left edge" offset. Note that this left edge is not necessarily going to be the leftmost character in the result, or the first character following the ellipses, but it will appear somewhere in the result.In no case will it return a String of length greater than
maxWidth
.StringUtils.abbreviate(null, *, *) = null StringUtils.abbreviate("", 0, 4) = "" StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..." StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..." StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno" StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno" StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno" StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException
- Parameters:
str
- the String to check, may be nulloffset
- left edge of source StringmaxWidth
- maximum length of result String, must be at least 4- Returns:
- abbreviated String,
null
if null String input - Throws:
IllegalArgumentException
- if the width is too small
-
isDefined
public static boolean isDefined(String parameter)
-
isNotDefined
public static boolean isNotDefined(String parameter)
-
requireDefined
public static void requireDefined(String name)
-
countMatches
public static int countMatches(String str, String subStr)
Counts how many times the substring appears in the larger string.
A
null
or empty ("") String input returns0
.StringUtils.countMatches(null, *) = 0 StringUtils.countMatches("", *) = 0 StringUtils.countMatches("abba", null) = 0 StringUtils.countMatches("abba", "") = 0 StringUtils.countMatches("abba", "a") = 2 StringUtils.countMatches("abba", "ab") = 1 StringUtils.countMatches("abba", "xxx") = 0
- Parameters:
str
- the text to check, may be nullsubStr
- the subtext to count, may be null- Returns:
- the number of occurrences, 0 if either CharSequence is
null
-
startsWith
public static boolean startsWith(CharSequence str, CharSequence prefix)
Check if a CharSequence starts with a specified prefix.
null
s are handled without exceptions. Twonull
references are considered to be equal. The comparison is case sensitive.StringUtils.startsWith(null, null) = true StringUtils.startsWith(null, "abc") = false StringUtils.startsWith("abcdef", null) = false StringUtils.startsWith("abcdef", "abc") = true StringUtils.startsWith("ABCDEF", "abc") = false
- Parameters:
str
- the CharSequence to check, may be nullprefix
- the prefix to find, may be null- Returns:
true
if the CharSequence starts with the prefix, case sensitive, or bothnull
- See Also:
String.startsWith(String)
-
splitByWholeSeparator
public static String[] splitByWholeSeparator(String str, String separator)
Splits the provided text into an array, separator string specified.
The separator(s) will not be included in the returned String array. Adjacent separators are treated as one separator.
A
null
input String returnsnull
. Anull
separator splits on whitespace.StringUtils.splitByWholeSeparator(null, *) = null StringUtils.splitByWholeSeparator("", *) = [] StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"] StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"] StringUtils.splitByWholeSeparator("ab:cd:ef", ":") = ["ab", "cd", "ef"] StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
- Parameters:
str
- the String to parse, may be nullseparator
- String containing the String to be used as a delimiter,null
splits on whitespace- Returns:
- an array of parsed Strings,
null
if null String was input
-
split
public static String[] split(String str, char separatorChar)
Splits the provided text into an array, separator specified. This is an alternative to using StringTokenizer.
The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.
A
null
input String returnsnull
.StringUtils.split(null, *) = null StringUtils.split("", *) = [] StringUtils.split("a.b.c", '.') = ["a", "b", "c"] StringUtils.split("a..b.c", '.') = ["a", "b", "c"] StringUtils.split("a:b:c", '.') = ["a:b:c"] StringUtils.split("a b c", ' ') = ["a", "b", "c"]
- Parameters:
str
- the String to parse, may be nullseparatorChar
- the character used as the delimiter- Returns:
- an array of parsed Strings,
null
if null String input - Since:
- 2.0
-
split
public static String[] split(String str, String separatorChars)
Splits the provided text into an array, separators specified. This is an alternative to using StringTokenizer.
The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.
A
null
input String returnsnull
. Anull
separatorChars splits on whitespace.StringUtils.split(null, *) = null StringUtils.split("", *) = [] StringUtils.split("abc def", null) = ["abc", "def"] StringUtils.split("abc def", " ") = ["abc", "def"] StringUtils.split("abc def", " ") = ["abc", "def"] StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
- Parameters:
str
- the String to parse, may be nullseparatorChars
- the characters used as the delimiters,null
splits on whitespace- Returns:
- an array of parsed Strings,
null
if null String input
-
capitalize
public static String capitalize(String str)
Capitalizes a String changing the first character to title case as per
Character.toTitleCase(int)
. No other characters are changed.A
null
input String returnsnull
.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,
null
if null String input - See Also:
uncapitalize(String)
-
uncapitalize
public static String uncapitalize(String str)
Uncapitalizes a String, changing the first character to lower case as per
Character.toLowerCase(int)
. No other characters are changed.A
null
input String returnsnull
.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,
null
if null String input - See Also:
capitalize(String)
-
normalize
public static String normalize(String string)
Normalizes the given string (which must be encoded into UTF-8) in order that the result contains only unified chars.Indeed, according to the environment of the user, sometimes it is sent data with combined characters which will make the server have a bad behavior, like throw an error on file download.
- Parameters:
string
- the string to normalize. There is no guarantee when the string is not encoded into UTF8.- Returns:
- the normalized string.
-
normalizeByRemovingAccent
public static String normalizeByRemovingAccent(String string)
Same treatment as the one ofnormalize(String)
but removes also the accented characters.- Parameters:
string
- the string to normalize. There is no guarantee when the string is not encoded into UTF8.- Returns:
- the normalized string.
-
defaultStringIfNotDefined
public static String defaultStringIfNotDefined(String string)
Returns either the passed in String, or if the String is
not defined
, an empty String ("").StringUtil.defaultStringIfNotDefined(null) = "" StringUtil.defaultStringIfNotDefined("") = "" StringUtil.defaultStringIfNotDefined(" ") = "" StringUtil.defaultStringIfNotDefined("bat") = "bat"
- Parameters:
string
- the String to check, may be null, blank or filled by spaces if the input isnot defined
, may be null, blank or filled by spaces- Returns:
- the passed in String, or the default if it was
null
- See Also:
isNotDefined(String)
,StringUtils.defaultString(String, String)
-
defaultStringIfNotDefined
public static String defaultStringIfNotDefined(String string, String defaultString)
Returns either the passed in String, or if the String is
not defined
, the value ofdefaultString
.StringUtil.defaultStringIfNotDefined(null, "NULL") = "NULL" StringUtil.defaultStringIfNotDefined("", "NULL") = "NULL" StringUtil.defaultStringIfNotDefined(" ", "NULL") = "NULL" StringUtil.defaultStringIfNotDefined("bat", "NULL") = "bat"
- Parameters:
string
- the String to check, may be null, blank or filled by spacesdefaultString
- the default String to return if the input isnot defined
, may be null, blank or filled by spaces- Returns:
- the passed in String, or the default if it was
null
- See Also:
isNotDefined(String)
,StringUtils.defaultString(String, String)
-
isInteger
public static boolean isInteger(String value)
-
asInt
public static int asInt(String value, int defaultValue)
-
isLong
public static boolean isLong(String value)
-
asFloat
public static float asFloat(String value)
-
isFloat
public static boolean isFloat(String value)
-
escapeQuote
public static String escapeQuote(String text)
- Parameters:
text
- the from which the quotes must be escaped (replaced by spaces in fact).- Returns:
- a String with all quotes replaced by spaces
-
toAcceptableFilename
public static String toAcceptableFilename(String name)
Replaces- Parameters:
name
- the original filename.- Returns:
- a String with all quotes replaced by spaces
-
format
public static String format(String label, Map<String,?> values)
Format a string by extending the principle of the the method format() of the class java.text.MessageFormat to string arguments. For instance, the string '{key}' contained in the original string to format will be replaced by the value corresponding to this key contained into the values map.- Parameters:
label
- The string to formatvalues
- The values to insert into the string- Returns:
- The formatted string, filled with values of the map.
-
truncate
public static String truncate(String text, int maxLength)
- Parameters:
text
- The string to truncate if its size is greater than the maximum length given as parameter.maxLength
- The maximum length required.- Returns:
- The truncated string followed by '...' if needed. Returns the string itself if its length is smaller than the required maximum length.
-
regexReplace
public static String regexReplace(String source, String regex, String replacement)
Replace parts of a text by an one replacement string. The text to replace is specified by a regex.- Parameters:
source
- the original textregex
- the regex that permits to identify parts of text to replacereplacement
- the replacement text- Returns:
- The source text modified
-
isValidEmailAddress
public static boolean isValidEmailAddress(String aEmailAddress)
Validate the form of an email address.Returns true only if
- aEmailAddress can successfully construct an
InternetAddress
- when parsed with "@" as delimiter, aEmailAddress contains two tokens which satisfy
The second condition arises since local email addresses, simply of the form "albert", for example, are valid for
InternetAddress
, but almost always undesired.- Parameters:
aEmailAddress
- the address to be validated- Returns:
- true is the address is a valid email address - false otherwise.
- aEmailAddress can successfully construct an
-
isValidHour
public static boolean isValidHour(String time)
-
getBooleanValue
public static boolean getBooleanValue(String expression)
Evaluate the expression and return true if expression equals "true", "yes", "y", "1" or "oui".- Parameters:
expression
- the expression to be evaluated- Returns:
- true if expression equals "true", "yes", "y", "1" or "oui".
-
areStringEquals
public static boolean areStringEquals(String s1, String s2)
Indicates if two Strings are equals, managing null.- Parameters:
s1
- the first String.s2
- the second String.- Returns:
- true ifthe two Strings are equals.
-
asBase64
public static String asBase64(byte[] binaryData)
Encodes the specified binary data into a text of Base64 characters.- Parameters:
binaryData
- the binary data to convert in Base64-based String.- Returns:
- a String representation of the binary data in Base64 characters.
-
fromBase64
public static byte[] fromBase64(String base64Text)
Decodes the specified text with Base64 characters in binary.- Parameters:
base64Text
- the text in Base64.- Returns:
- the binary representation of the text.
-
splitString
public static Iterable<String> splitString(String str)
Splits the provided text into an array, using whitespace as the separator. Whitespace is defined by
Character.isWhitespace(char)
.The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.
A
null
input String returnsnull
.StringUtils.split(null) = null StringUtils.split("") = empty list StringUtils.split("abc def") = ["abc", "def"] StringUtils.split("abc def") = ["abc", "def"] StringUtils.split(" abc ") = ["abc"]
- Parameters:
str
- the String to parse, may be null- Returns:
- an array of parsed Strings,
null
if null String input
-
splitString
public static Iterable<String> splitString(String str, char separatorChar)
Splits the provided text into an array, separator specified. This is an alternative to using StringTokenizer.
The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.
A
null
input String returnsnull
.StringUtils.split(null, *) = null StringUtils.split("", *) = empty list StringUtils.split("a.b.c", '.') = ["a", "b", "c"] StringUtils.split("a..b.c", '.') = ["a", "b", "c"] StringUtils.split("a:b:c", '.') = ["a:b:c"] StringUtils.split("a b c", ' ') = ["a", "b", "c"]
- Parameters:
str
- the String to parse, may be nullseparatorChar
- the character used as the delimiter- Returns:
- an array of parsed Strings,
null
if null String input
-
doubleAntiSlash
public static String doubleAntiSlash(String path)
Doubles the anti-slash character in a path value.- Parameters:
path
- the String representing a path.- Returns:
- the path corrected with the anti-slash doubled.
-
-