public final class Strings extends Object
The escapeMarkup() and toMultilineMarkup() methods are useful for turning normal Java Strings into HTML strings.
The lastPathComponent(), firstPathComponent(), afterFirstPathComponent() and beforeLastPathComponent() methods can chop up a String into path components using a separator character. If the separator cannot be found the original String is returned.
Similarly, the beforeLast(), beforeFirst(), afterFirst() and afterLast() methods return sections before and after a separator character. But if the separator cannot be found, an empty string is returned.
Some other miscellaneous methods will strip a given ending off a String if it can be found (stripEnding()), replace all occurrences of one String with another (replaceAll), do type conversions (toBoolean(), toChar(), toString()), check a String for emptiness (isEmpty()), convert a Throwable to a String (toString(Throwable)) or capitalize a String (capitalize()).
Modifier and Type | Field and Description |
---|---|
static String |
LINE_SEPARATOR
The line separator for the current platform.
|
static String |
SESSION_ID_PARAM_NAME
The name of the parameter used to keep the session id.
|
Modifier and Type | Method and Description |
---|---|
static String |
afterFirst(String s,
char c)
Returns everything after the first occurrence of the given character in s.
|
static String |
afterFirstPathComponent(String path,
char separator)
Gets everything after the first path component of a path using a given separator.
|
static String |
afterLast(String s,
char c)
Returns everything after the last occurrence of the given character in s.
|
static String |
beforeFirst(String s,
char c)
Returns everything before the first occurrence of the given character in s.
|
static String |
beforeLast(String s,
char c)
Returns everything before the last occurrence of the given character in s.
|
static String |
beforeLastPathComponent(String path,
char separator)
Gets everything before the last path component of a path using a given separator.
|
static String |
capitalize(String s)
Capitalizes a string.
|
static String |
defaultIfEmpty(String originalString,
String defaultValue)
Returns the original string if this one is not empty (i.e.
|
static CharSequence |
escapeMarkup(CharSequence s)
Converts a Java String to an HTML markup string, but does not convert normal spaces to
non-breaking space entities (<nbsp>).
|
static CharSequence |
escapeMarkup(CharSequence s,
boolean escapeSpaces)
Converts a Java String to an HTML markup String by replacing illegal characters with HTML
entities where appropriate.
|
static CharSequence |
escapeMarkup(CharSequence s,
boolean escapeSpaces,
boolean convertToHtmlUnicodeEscapes)
Converts a Java String to an HTML markup String by replacing illegal characters with HTML
entities where appropriate.
|
static String |
firstPathComponent(String path,
char separator)
Gets the first path component of a path using a given separator.
|
static String |
fromEscapedUnicode(String escapedUnicodeString)
Converts encoded \uxxxx to unicode chars and changes special saved chars to their
original forms.
|
static int |
getLevenshteinDistance(CharSequence s,
CharSequence t)
Find the Levenshtein distance between two Strings.
|
static int |
indexOf(CharSequence sequence,
char ch)
returns the zero-based index of a character within a char sequence.
|
static boolean |
isEmpty(CharSequence string)
Checks whether the
string is considered empty. |
static boolean |
isEqual(String string1,
String string2)
Checks whether two strings are equals taken care of 'null' values and treating 'null' same as
trim(string).equals("")
|
static boolean |
isTrue(String s)
Converts the text in
s to a corresponding boolean. |
static String |
join(String separator,
List<String> fragments)
Joins string fragments using the specified separator
|
static String |
join(String separator,
String... fragments)
Joins string fragments using the specified separator
|
static String |
lastPathComponent(String path,
char separator)
Gets the last path component of a path using a given separator.
|
static int |
lengthInBytes(String string,
Charset charset)
Calculates the length of string in bytes, uses specified
charset if provided. |
static CharSequence |
replaceAll(CharSequence s,
CharSequence searchFor,
CharSequence replaceWith)
Replace all occurrences of one string replaceWith another string.
|
static String |
replaceHtmlEscapeNumber(String str)
Replace HTML numbers like 值 by the appropriate character.
|
static String[] |
split(String s,
char c)
Simpler, faster version of String.split() for splitting on a simple character.
|
static boolean |
startsWith(String str,
String prefix,
boolean caseSensitive)
Extended
String.startsWith(String) with support for case sensitivity |
static String |
stripEnding(String s,
String ending)
Strips the ending from the string
s . |
static String |
stripJSessionId(String url)
Strip any jsessionid and possibly other redundant info that might be in our way.
|
static Boolean |
toBoolean(String s)
Converts the string s to a Boolean.
|
static char |
toChar(String s)
Converts the 1 character string s to a character.
|
static <T extends Enum<T>> |
toEnum(CharSequence value,
Class<T> enumClass)
Return this value as en enum value.
|
static String |
toEscapedUnicode(String unicodeString)
Converts unicodes to encoded \uxxxx.
|
static String |
toHexString(byte[] bytes)
convert byte array to hex string
|
static CharSequence |
toMultilineMarkup(CharSequence s)
Converts a String to multiline HTML markup by replacing newlines with line break entities
(<br/>) and multiple occurrences of newline with paragraph break entities (<p>).
|
static String |
toString(Object object)
Converts the given object to a string.
|
static String |
toString(Throwable throwable)
Converts a Throwable to a string.
|
static CharSequence |
unescapeMarkup(String markup)
Unescapes the escaped entities in the
markup passed. |
public static final String LINE_SEPARATOR
public static final String SESSION_ID_PARAM_NAME
public static String afterFirst(String s, char c)
s
- The stringc
- The characterpublic static String afterFirstPathComponent(String path, char separator)
For example, afterFirstPathComponent("foo:bar:baz", ':') would return "bar:baz" and afterFirstPathComponent("foo", ':') would return "".
path
- The path to parseseparator
- The path separator characterpublic static String afterLast(String s, char c)
s
- The stringc
- The characterpublic static String beforeFirst(String s, char c)
s
- The stringc
- The characterpublic static String beforeLast(String s, char c)
s
- The stringc
- The characterpublic static String beforeLastPathComponent(String path, char separator)
For example, beforeLastPathComponent("foo.bar.baz", '.') would return "foo.bar" and beforeLastPathComponent("foo", '.') would return "".
path
- The path to parseseparator
- The path separator characterpublic static String capitalize(String s)
s
- The stringpublic static CharSequence escapeMarkup(CharSequence s)
s
- The characters to escapeescapeMarkup(CharSequence, boolean)
public static CharSequence escapeMarkup(CharSequence s, boolean escapeSpaces)
s
- The characters to escapeescapeSpaces
- True to replace ' ' with nonbreaking spacepublic static CharSequence escapeMarkup(CharSequence s, boolean escapeSpaces, boolean convertToHtmlUnicodeEscapes)
s
- The characters to escapeescapeSpaces
- True to replace ' ' with nonbreaking spaceconvertToHtmlUnicodeEscapes
- True to convert non-7 bit characters to unicode HTML (...)public static CharSequence unescapeMarkup(String markup)
markup
passed.markup
- The source String
to unescape.null if the input is null
public static String firstPathComponent(String path, char separator)
For example, firstPathComponent("foo.bar", '.') would return "foo" and firstPathComponent("foo", '.') would return "foo".
path
- The path to parseseparator
- The path separator characterpublic static String fromEscapedUnicode(String escapedUnicodeString)
escapedUnicodeString
- escaped unicode string, like '你好'.public static boolean isEmpty(CharSequence string)
string
is considered empty. Empty means that the string may
contain whitespace, but no visible characters.
"\n\t " is considered empty, while " a" is not.string
- The stringpublic static boolean isEqual(String string1, String string2)
string1
- string2
- public static boolean isTrue(String s) throws StringValueConversionException
s
to a corresponding boolean. On, yes, y, true and 1 are
converted to true
. Off, no, n, false and 0 (zero) are converted to
false
. An empty string is converted to false
. Conversion is
case-insensitive, and does not take internationalization into account.
'Ja', 'Oui', 'Igen', 'Nein', 'Nee', 'Non', 'Nem' are all illegal values.s
- the value to convert into a booleans
StringValueConversionException
- when the value of s
is not recognized.public static String join(String separator, List<String> fragments)
separator
- fragments
- public static String join(String separator, String... fragments)
separator
- fragments
- public static String lastPathComponent(String path, char separator)
For example, lastPathComponent("foo.bar", '.') would return "bar" and lastPathComponent("foo", '.') would return "foo".
path
- The path to parseseparator
- The path separator characterpublic static CharSequence replaceAll(CharSequence s, CharSequence searchFor, CharSequence replaceWith)
s
- The string to processsearchFor
- The value to search forreplaceWith
- The value to searchFor replaceWithpublic static String replaceHtmlEscapeNumber(String str)
str
- The text to be evaluatedpublic static String[] split(String s, char c)
s
- The string to splitc
- The character to split onpublic static String stripEnding(String s, String ending)
s
.s
- The string to stripending
- The ending to strip offpublic static String stripJSessionId(String url)
url
- The url to strippublic static Boolean toBoolean(String s) throws StringValueConversionException
isTrue
for valid values of s.s
- The string to convert.TRUE
when isTrue(s)
.StringValueConversionException
- when s is not a valid valueisTrue(String)
public static char toChar(String s) throws StringValueConversionException
s
- The 1 character string to convert to a char.StringValueConversionException
- when the string is longer or shorter than 1 character, or null
.public static String toEscapedUnicode(String unicodeString)
unicodeString
- The unicode stringpublic static CharSequence toMultilineMarkup(CharSequence s)
s
- String to transformpublic static String toString(Object object)
throwables
and String arrays of length 1 (in which case it just returns to string in that
array, as this is a common thing to have in the Servlet API).object
- The objectpublic static String toString(Throwable throwable)
throwable
- The throwablepublic static int lengthInBytes(String string, Charset charset)
charset
if provided.string
- charset
- (optional) character set to use when converting string to bytespublic static boolean startsWith(String str, String prefix, boolean caseSensitive)
String.startsWith(String)
with support for case sensitivitystr
- prefix
- caseSensitive
- true
if str
starts with prefix
public static int indexOf(CharSequence sequence, char ch)
sequence.toString().indexOf(ch)
.sequence
- character sequencech
- character to search for-1
if not foundpublic static int getLevenshteinDistance(CharSequence s, CharSequence t)
Find the Levenshtein distance between two Strings.
This is the number of changes needed to change one String into another, where each change is a single character modification (deletion, insertion or substitution).
The previous implementation of the Levenshtein distance algorithm was from http://www.merriampark.com/ld.htm
Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError which
can occur when my Java implementation is used with very large strings.
This implementation of the Levenshtein distance algorithm is from http://www.merriampark.com/ldjava.htm
Strings.getLevenshteinDistance(null, *) = IllegalArgumentException Strings.getLevenshteinDistance(*, null) = IllegalArgumentException Strings.getLevenshteinDistance("","") = 0 Strings.getLevenshteinDistance("","a") = 1 Strings.getLevenshteinDistance("aaapppp", "") = 7 Strings.getLevenshteinDistance("frog", "fog") = 1 Strings.getLevenshteinDistance("fly", "ant") = 3 Strings.getLevenshteinDistance("elephant", "hippo") = 7 Strings.getLevenshteinDistance("hippo", "elephant") = 7 Strings.getLevenshteinDistance("hippo", "zzzzzzzz") = 8 Strings.getLevenshteinDistance("hello", "hallo") = 1Copied from Apache commons-lang StringUtils 3.0
s
- the first String, must not be nullt
- the second String, must not be nullIllegalArgumentException
- if either String input null
public static String toHexString(byte[] bytes)
bytes
- bytes to convert to hexadecimal representationpublic static <T extends Enum<T>> T toEnum(CharSequence value, Class<T> enumClass)
value
- the value to convert to an enum valueenumClass
- the enum typepublic static String defaultIfEmpty(String originalString, String defaultValue)
isEmpty(CharSequence)
returns false),
otherwise the default one is returned. The default string might be itself an empty one.originalString
- the original sting valuedefaultValue
- the default string to return if the original is emptyCopyright © 2006–2022 Apache Software Foundation. All rights reserved.