Class MoreStrings
- java.lang.Object
-
- io.cui.tools.string.MoreStrings
-
public final class MoreStrings extends Object
Provides some extensions to String handling like com.google.common.base.Strings. It was created using different source, see authors- Author:
- Oliver Wolff, Sven Haag, https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/StringUtils.java, https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java, https://github.com/spring-projects/spring-framework/blob/v5.1.8.RELEASE/spring-core/src/main/java/org/springframework/util/StringUtils.java, com.google.common.base.Strings
-
-
Field Summary
Fields Modifier and Type Field Description static StringEMPTYThe empty String"".static intINDEX_NOT_FOUNDRepresents a failed index search.static StringSPACEA String for a space character.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static Optional<String>coalesce(Predicate<String> checker, String... values)static intcountMatches(CharSequence str, CharSequence sub)Counts how many times the substring appears in the larger string.static StringemptyToNull(String string)Returns the given string if it is nonempty;nullotherwise.static StringensureEndsWith(@NonNull String value, @NonNull String suffix)static Optional<String>firstNonBlank(String... values)static Optional<String>firstNonEmpty(String... values)static booleanhasNonWhitespaceChar(CharSequence str)Check whether the givenStringcontains actual text.static intindexOf(CharSequence seq, int searchChar)Returns the index withinseqof the first occurrence of the specified character.static intindexOf(CharSequence cs, int searchChar, int start)Returns the index withincsof the first occurrence of the specified character, starting the search at the specified index.static intindexOf(CharSequence cs, CharSequence searchChar, int start)Used by the indexOf(CharSequence methods) as a green implementation of indexOf.static booleanisAllLowerCase(CharSequence cs)Checks if the CharSequence contains only lowercase characters.static booleanisAllUpperCase(CharSequence cs)Checks if the CharSequence contains only uppercase characters.static 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 booleanisNotBlank(CharSequence cs)NOTofisBlank(CharSequence).static booleanisNumeric(CharSequence cs)Checks if the CharSequence contains only Unicode digits.static booleanisPresent(CharSequence cs)Checks if a CharSequence is not empty ("") or null.static StringleftPad(String str, int size)Left pad a String with spaces (' ').static StringleftPad(String str, int size, char padChar)Left pad a String with a specified character.static StringleftPad(String str, int size, String padStr)Left pad a String with a specified String.static StringlenientFormat(String template, Object... args)Returns the giventemplatestring with each occurrence of"%s"replaced with the corresponding argument value fromargs; or, if the placeholder and argument counts do not match, returns a best-effort form of that string.static StringnullToEmpty(String string)Returns the given string if it is non-null; the empty string otherwise.static Stringrepeat(char ch, int repeat)Returns padding using the specified delimiter repeated to a given length.static StringrequireNotEmpty(String underCheck)Checks a string for being non-null and not empty (checks without trimming) Throws anIllegalArgumentExceptionif String is null or emptystatic StringrequireNotEmpty(String underCheck, String attributeName)Checks a string for being non-null and not empty (checks without trimming) Throws anIllegalArgumentExceptionif String is null or emptystatic StringrequireNotEmptyTrimmed(String underCheck)Checks a string for being non-null and not empty (checks with trimming) Throws anIllegalArgumentExceptionif String is null or emptystatic StringrequireNotEmptyTrimmed(String underCheck, String attributeName)Checks a string for being non-null and not empty (checks with trimming) Throws anIllegalArgumentExceptionif String is null or emptystatic StringstripEnd(String str, String stripChars)Strips any of a set of characters from the end of a String.static StringtrimOrNull(String string)Null-safe trimming of a String value.static Stringunquote(String original)"Unquotes" a String, saying if the given String starts and ends with the token "'" or """ the quotes will be stripped
-
-
-
Field Detail
-
EMPTY
public static final String EMPTY
The empty String"".- See Also:
- Constant Field Values
-
SPACE
public static final String SPACE
A String for a space character.- See Also:
- Constant Field Values
-
INDEX_NOT_FOUND
public static final int INDEX_NOT_FOUND
Represents a failed index search.- See Also:
- Constant Field Values
-
-
Method Detail
-
unquote
public static String unquote(String original)
"Unquotes" a String, saying if the given String starts and ends with the token "'" or """ the quotes will be stripped- Parameters:
original- may be null or empty- Returns:
- the unquoted String or the original in none could be found
-
isAllLowerCase
public static boolean isAllLowerCase(CharSequence cs)
Checks if the CharSequence contains only lowercase characters.
nullwill returnfalse. An empty CharSequence (length()=0) will returnfalse.MoreStrings.isAllLowerCase(null) = false MoreStrings.isAllLowerCase("") = false MoreStrings.isAllLowerCase(" ") = false MoreStrings.isAllLowerCase("abc") = true MoreStrings.isAllLowerCase("abC") = false MoreStrings.isAllLowerCase("ab c") = false MoreStrings.isAllLowerCase("ab1c") = false MoreStrings.isAllLowerCase("ab/c") = false- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif only contains lowercase characters, and is non-null
-
isAllUpperCase
public static boolean isAllUpperCase(CharSequence cs)
Checks if the CharSequence contains only uppercase characters.
nullwill returnfalse. An empty String (length()=0) will returnfalse.MoreStrings.isAllUpperCase(null) = false MoreStrings.isAllUpperCase("") = false MoreStrings.isAllUpperCase(" ") = false MoreStrings.isAllUpperCase("ABC") = true MoreStrings.isAllUpperCase("aBC") = false MoreStrings.isAllUpperCase("A C") = false MoreStrings.isAllUpperCase("A1C") = false MoreStrings.isAllUpperCase("A/C") = false- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif only contains uppercase characters, and is non-null
-
isEmpty
public static boolean isEmpty(CharSequence cs)
Checks if a CharSequence is empty ("") or null.
MoreStrings.isEmpty(null) = true MoreStrings.isEmpty("") = true MoreStrings.isEmpty(" ") = false MoreStrings.isEmpty("bob") = false MoreStrings.isEmpty(" bob ") = false- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif the CharSequence is empty or null
-
isPresent
public static boolean isPresent(CharSequence cs)
Checks if a CharSequence is not empty ("") or null.
MoreStrings.isEmpty(null) = false MoreStrings.isEmpty("") = false MoreStrings.isEmpty(" ") = true- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif the CharSequence is not empty
-
isNumeric
public static boolean isNumeric(CharSequence cs)
Checks if the CharSequence contains only Unicode digits. A decimal point is not a Unicode digit and returns false.
nullwill returnfalse. An empty CharSequence (length()=0) will returnfalse.Note that the method does not allow for a leading sign, either positive or negative. Also, if a String passes the numeric test, it may still generate a NumberFormatException when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range for int or long respectively.
MoreStrings.isNumeric(null) = false MoreStrings.isNumeric("") = false MoreStrings.isNumeric(" ") = false MoreStrings.isNumeric("123") = true MoreStrings.isNumeric("१२३") = true MoreStrings.isNumeric("12 3") = false MoreStrings.isNumeric("ab2c") = false MoreStrings.isNumeric("12-3") = false MoreStrings.isNumeric("12.3") = false MoreStrings.isNumeric("-123") = false MoreStrings.isNumeric("+123") = false- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif only contains digits, and is non-null
-
isBlank
public static boolean isBlank(CharSequence cs)
Checks if a CharSequence is empty (""), null or whitespace only.
Whitespace is defined by
Character.isWhitespace(char).MoreStrings.isBlank(null) = true MoreStrings.isBlank("") = true MoreStrings.isBlank(" ") = true MoreStrings.isBlank("bob") = false MoreStrings.isBlank(" bob ") = false- Parameters:
cs- the CharSequence to check, may be null- Returns:
trueif the CharSequence is null, empty or whitespace only
-
isNotBlank
public static boolean isNotBlank(CharSequence cs)
NOTofisBlank(CharSequence).Checks if a CharSequence is not empty (""), null or contains whitespaces only.
Whitespace is defined by
Character.isWhitespace(char).MoreStrings.isBlank(null) = false MoreStrings.isBlank("") = false MoreStrings.isBlank(" ") = false MoreStrings.isBlank("bob") = true MoreStrings.isBlank(" bob ") = true- Parameters:
cs- to be checked- Returns:
trueif the given string is no blank,falseotherwise
-
countMatches
public static int countMatches(CharSequence str, CharSequence sub)
Counts how many times the substring appears in the larger string.
A
nullor empty ("") String input returns0.MoreStrings.countMatches(null, *) = 0 MoreStrings.countMatches("", *) = 0 MoreStrings.countMatches("abba", null) = 0 MoreStrings.countMatches("abba", "") = 0 MoreStrings.countMatches("abba", "a") = 2 MoreStrings.countMatches("abba", "ab") = 1 MoreStrings.countMatches("abba", "xxx") = 0- Parameters:
str- the CharSequence to check, may be nullsub- the substring to count, may be null- Returns:
- the number of occurrences, 0 if either CharSequence is
null
-
leftPad
public static String leftPad(String str, int size)
Left pad a String with spaces (' ').
The String is padded to the size of
size.MoreStrings.leftPad(null, *) = null MoreStrings.leftPad("", 3) = " " MoreStrings.leftPad("bat", 3) = "bat" MoreStrings.leftPad("bat", 5) = " bat" MoreStrings.leftPad("bat", 1) = "bat" MoreStrings.leftPad("bat", -1) = "bat"- Parameters:
str- the String to pad out, may be nullsize- the size to pad to- Returns:
- left padded String or original String if no padding is necessary,
nullif null String input
-
leftPad
public static String leftPad(String str, int size, char padChar)
Left pad a String with a specified character.
Pad to a size of
size.MoreStrings.leftPad(null, *, *) = null MoreStrings.leftPad("", 3, 'z') = "zzz" MoreStrings.leftPad("bat", 3, 'z') = "bat" MoreStrings.leftPad("bat", 5, 'z') = "zzbat" MoreStrings.leftPad("bat", 1, 'z') = "bat" MoreStrings.leftPad("bat", -1, 'z') = "bat"- Parameters:
str- the String to pad out, may be nullsize- the size to pad topadChar- the character to pad with- Returns:
- left padded String or original String if no padding is necessary,
nullif null String input
-
leftPad
public static String leftPad(String str, int size, String padStr)
Left pad a String with a specified String.
Pad to a size of
size.MoreStrings.leftPad(null, *, *) = null MoreStrings.leftPad("", 3, "z") = "zzz" MoreStrings.leftPad("bat", 3, "yz") = "bat" MoreStrings.leftPad("bat", 5, "yz") = "yzbat" MoreStrings.leftPad("bat", 8, "yz") = "yzyzybat" MoreStrings.leftPad("bat", 1, "yz") = "bat" MoreStrings.leftPad("bat", -1, "yz") = "bat" MoreStrings.leftPad("bat", 5, null) = " bat" MoreStrings.leftPad("bat", 5, "") = " bat"- Parameters:
str- the String to pad out, may be nullsize- the size to pad topadStr- the String to pad with, null or empty treated as single space- Returns:
- left padded String or original String if no padding is necessary,
nullif null String input
-
repeat
public static String repeat(char ch, int repeat)
Returns padding using the specified delimiter repeated to a given length.
MoreStrings.repeat('e', 0) = "" MoreStrings.repeat('e', 3) = "eee" MoreStrings.repeat('e', -2) = ""Note: this method does not support padding with Unicode Supplementary Characters as they require a pair of
chars to be represented. If you are needing to support full I18N of your applications consider usingrepeat(String, int)instead.- Parameters:
ch- character to repeatrepeat- number of times to repeat char, negative treated as zero- Returns:
- String with repeated character
-
stripEnd
public static String stripEnd(String str, String stripChars)
Strips any of a set of characters from the end of a String.
A
nullinput String returnsnull. An empty string ("") input returns the empty string.If the stripChars String is
null, whitespace is stripped as defined byCharacter.isWhitespace(char).MoreStrings.stripEnd(null, *) = null MoreStrings.stripEnd("", *) = "" MoreStrings.stripEnd("abc", "") = "abc" MoreStrings.stripEnd("abc", null) = "abc" MoreStrings.stripEnd(" abc", null) = " abc" MoreStrings.stripEnd("abc ", null) = "abc" MoreStrings.stripEnd(" abc ", null) = " abc" MoreStrings.stripEnd(" abcyx", "xyz") = " abc" MoreStrings.stripEnd("120.00", ".0") = "12"- Parameters:
str- the String to remove characters from, may be nullstripChars- the set of characters to remove, null treated as whitespace- Returns:
- the stripped String,
nullif null String input
-
indexOf
public static int indexOf(CharSequence seq, int searchChar)
Returns the index withinseqof the first occurrence of the specified character. If a character with valuesearchCharoccurs in the character sequence represented byseqCharSequenceobject, then the index (in Unicode code units) of the first such occurrence is returned. For values ofsearchCharin the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that:
is true. For other values ofthis.charAt(k) == searchChar
searchChar, it is the smallest value k such that:
is true. In either case, if no such character occurs inthis.codePointAt(k) == searchChar
seq, thenINDEX_NOT_FOUND (-1)is returned.Furthermore, a
nullor empty ("") CharSequence will returnINDEX_NOT_FOUND (-1).MoreStrings.indexOf(null, *) = -1 MoreStrings.indexOf("", *) = -1 MoreStrings.indexOf("aabaabaa", 'a') = 0 MoreStrings.indexOf("aabaabaa", 'b') = 2- Parameters:
seq- the CharSequence to check, may be nullsearchChar- the character to find- Returns:
- the first index of the search character,
-1 if no match or
nullstring input
-
indexOf
public static int indexOf(CharSequence cs, int searchChar, int start)
Returns the index withincsof the first occurrence of the specified character, starting the search at the specified index.If a character with value
searchCharoccurs in the character sequence represented by thecsobject at an index no smaller thanstart, then the index of the first such occurrence is returned. For values ofsearchCharin the range from 0 to 0xFFFF (inclusive), this is the smallest value k such that:
is true. For other values of(this.charAt(k) == searchChar) && (k >= start)
searchChar, it is the smallest value k such that:
is true. In either case, if no such character occurs inm(this.codePointAt(k) == searchChar) && (k >= start)
csat or after positionstart, then-1is returned.There is no restriction on the value of
start. If it is negative, it has the same effect as if it were zero: the entireCharSequencemay be searched. If it is greater than the length ofcs, it has the same effect as if it were equal to the length ofcs:-1is returned.All indices are specified in
charvalues (Unicode code units).- Parameters:
cs- theCharSequenceto be processed, not nullsearchChar- the char to be searched forstart- the start index, negative starts at the string start- Returns:
- the index where the search char was found, -1 if not found
-
indexOf
public static int indexOf(CharSequence cs, CharSequence searchChar, int start)
Used by the indexOf(CharSequence methods) as a green implementation of indexOf.- Parameters:
cs- theCharSequenceto be processedsearchChar- theCharSequenceto be searched forstart- the start index- Returns:
- the index where the search sequence was found
-
hasNonWhitespaceChar
public static boolean hasNonWhitespaceChar(CharSequence str)
Check whether the givenStringcontains actual text.More specifically, this method returns
trueif theStringis notnull, its length is greater than 0, and it contains at least one non-whitespace character.- Parameters:
str- theStringto check (maybenull)- Returns:
trueif theStringis notnull, its length is greater than 0, and it does not contain whitespace only
-
requireNotEmpty
public static String requireNotEmpty(String underCheck)
Checks a string for being non-null and not empty (checks without trimming) Throws anIllegalArgumentExceptionif String is null or empty- Parameters:
underCheck-- Returns:
- the given String
-
requireNotEmpty
public static String requireNotEmpty(String underCheck, String attributeName)
Checks a string for being non-null and not empty (checks without trimming) Throws anIllegalArgumentExceptionif String is null or empty- Parameters:
underCheck-attributeName- used for the creation of the error text- Returns:
- the given String
-
requireNotEmptyTrimmed
public static String requireNotEmptyTrimmed(String underCheck)
Checks a string for being non-null and not empty (checks with trimming) Throws anIllegalArgumentExceptionif String is null or empty- Parameters:
underCheck-- Returns:
- the given String
-
requireNotEmptyTrimmed
public static String requireNotEmptyTrimmed(String underCheck, String attributeName)
Checks a string for being non-null and not empty (checks with trimming) Throws anIllegalArgumentExceptionif String is null or empty- Parameters:
underCheck-attributeName- used for the creation of the error text- Returns:
- the given String
-
nullToEmpty
public static String nullToEmpty(String string)
Returns the given string if it is non-null; the empty string otherwise.- Parameters:
string- the string to test and possibly return- Returns:
stringitself if it is non-null;""if it is null
-
emptyToNull
public static String emptyToNull(String string)
Returns the given string if it is nonempty;nullotherwise.- Parameters:
string- the string to test and possibly return- Returns:
stringitself if it is nonempty;nullif it is empty or null
-
trimOrNull
public static String trimOrNull(String string)
Null-safe trimming of a String value.- Parameters:
string- to be trimmed- Returns:
nullif the string isnullotherwise the trimmed string
-
lenientFormat
public static String lenientFormat(String template, Object... args)
Returns the giventemplatestring with each occurrence of"%s"replaced with the corresponding argument value fromargs; or, if the placeholder and argument counts do not match, returns a best-effort form of that string. Will not throw an exception under normal conditions.Note: For most string-formatting needs, use
String.format,PrintWriter.format, and related methods. These support the full range of format specifiers, and alert you to usage errors by throwingIllegalFormatException.In certain cases, such as outputting debugging information or constructing a message to be used for another unchecked exception, an exception during string formatting would serve little purpose except to supplant the real information you were trying to provide. These are the cases this method is made for; it instead generates a best-effort string with all supplied argument values present. This method is also useful in environments such as GWT where
String.formatis not available.Warning: Only the exact two-character placeholder sequence
"%s"is recognized.- Parameters:
template- a string containing zero or more"%s"placeholder sequences.nullis treated as the four-character string"null".args- the arguments to be substituted into the message template. The first argument specified is substituted for the first occurrence of"%s"in the template, and so forth. Anullargument is converted to the four-character string"null"; non-null values are converted to strings usingObject.toString().- Returns:
- the resulting formatting String
-
ensureEndsWith
public static String ensureEndsWith(@NonNull @NonNull String value, @NonNull @NonNull String suffix)
- Parameters:
value- to be processedsuffix- to be present- Returns:
- value with suffix
-
coalesce
public static Optional<String> coalesce(Predicate<String> checker, String... values)
- Parameters:
checker- the predicate to check each given value against. it decides if a value qualifies to be returned.values- to be evaluated- Returns:
- first string that is accepted by the given
PredicateorOptional.empty()
-
firstNonEmpty
public static Optional<String> firstNonEmpty(String... values)
- Parameters:
values- to be evaluated- Returns:
- first string that is not
isEmpty(CharSequence)
-
firstNonBlank
public static Optional<String> firstNonBlank(String... values)
- Parameters:
values- to be evaluated- Returns:
- first string that is not
isBlank(CharSequence)
-
-