Class StringUtils
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final AsciiSetCharacters considered common separators (comma/semicolon/colon/pipe/tab).static final StringWindows-style carriage-return/line-feed sequence.static final AsciiSetDigits 0-9 represented as anAsciiSet.static final AsciiSetDigits 0-9 represented as anAsciiSet.static final StringZero-length string constant.static final AsciiSetCharacters allowed at the beginning of a numeric literal.static final PatternFloating-point literal validation pattern used byDouble.valueOf(String).static final AsciiSetHexadecimal digit characters.static final AsciiSetCharacters allowed in HTTP headers (including quoted strings and comments).static final AsciiSetLetters a-z and A-Z represented as anAsciiSet.static final AsciiSetLowercase letters a-z represented as anAsciiSet.static final AsciiSetUppercase letters A-Z represented as anAsciiSet.static final AsciiSetCharacters escaped when parsing key/value pairs.static final StringUnix-style newline character.Predicate that filters outnulland empty strings.static final AsciiSetCharacters that can appear anywhere in a numeric literal.static final AsciiSetOctal digit characters.static final AsciiSetCharacters escaped when parsing quoted strings.static final StringSingle-space character constant.static final StringHorizontal tab character constant.static final AsciiSetCharacters considered part of a URI when encoding paths.static final AsciiSetCharacters that may appear unescaped in path segments when URL-encoding.static final AsciiSetCharacters that never require URL encoding per RFC 3986.static final AsciiSetExtended set of characters that are typically safe to leave unencoded.static final AsciiSetVowel characters a, e, i, o, u (both uppercase and lowercase) represented as anAsciiSet.static final AsciiSetAll standard whitespace characters (space, tab, newline, carriage return, form feed, vertical tab). -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic Stringabbreviate(String in, int length) Abbreviates a string using ellipses if it exceeds the specified length.static StringBuilderappend(StringBuilder sb, String in) Appends a string to a StringBuilder, creating a new one if null.static StringBuilderappendIfNotBlank(StringBuilder sb, String str) Appends a string to a StringBuilder if the string is not blank.static StringBuilderappendIfNotEmpty(StringBuilder sb, String str) Appends a string to a StringBuilder if the string is not empty.static StringBuilderappendWithSeparator(StringBuilder sb, String str, String separator) Appends a string to a StringBuilder with a separator, only adding the separator if the StringBuilder is not empty.static Stringarticlized(String subject) Adds the appropriate indefinite article ('a' or 'an') before a word.static byte[]base64Decode(String in) BASE64-decodes the specified string.static StringShortcut for callingbase64Decode(String) and converting the result to a UTF-8 encoded string.static Stringbase64Encode(byte[] in) BASE64-encodes the specified byte array.static StringShortcut for callingbase64Encode(in.getBytes("UTF-8" ))static StringbuildString(Consumer<StringBuilder> builder) Builds a string using a functional approach with a StringBuilder.static StringConverts a string to camelCase format.static Stringcapitalize(String str) Capitalizes the first character of a string.Converts a comma-delimited string to a list.static LinkedHashSet<String>Converts a comma-delimited string to a set.static charReturns the character at the specified index in the string without throwing exceptions.static StringCleans a string by removing control characters and normalizing whitespace.static intCompares two strings lexicographically, but gracefully handlesnull values.static intcompareIgnoreCase(String str1, String str2) Compares two strings lexicographically, ignoring case.static byte[]Compresses a UTF-8 string into a GZIP-compressed byte array.static booleanChecks if a string contains the specified character.static booleancontains(String value, CharSequence substring) Null-safeString.contains(CharSequence)operation.static booleanNull-safe check if a string contains another string.static booleancontainsAll(String s, char... values) Checks if a string contains all of the specified characters.static booleancontainsAll(String s, CharSequence... values) Checks if a string contains all of the specified substrings.static booleancontainsAll(String s, String... values) Checks if a string contains all of the specified substrings.static booleancontainsAny(String s, char... values) Checks if a string contains any of the specified characters.static booleancontainsAny(String s, CharSequence... values) Checks if a string contains any of the specified substrings.static booleancontainsAny(String s, String... values) Checks if a string contains any of the specified substrings.static booleancontainsIgnoreCase(String str, String search) Checks if a string contains a substring, ignoring case.static intcountChars(String s, char c) Counts the number of occurrences of the specified character in the specified string.static intcountMatches(String str, String search) Counts the number of occurrences of a substring within a string.static StringDebug method for rendering non-ASCII character sequences.static Stringdecompress(byte[] is) Decompresses a GZIP-compressed byte array into a UTF-8 string.static StringdefaultIfBlank(String str, String defaultStr) Returns the specified string, or the default string if that string isnull or blank.static StringdefaultIfEmpty(String str, String defaultStr) Returns the specified string, or the default string if that string isnull or empty.static intdiffPosition(String s1, String s2) Finds the position where the two strings first differ.static intdiffPositionIc(String s1, String s2) Finds the position where the two strings first differ, ignoring case.static String[]Removes duplicate elements from a string array, preserving order.static String[]doubleMetaphone(String str) Generates a Double Metaphone code for a string.static StringemptyIfNull(String str) Returns the specified string, or an empty string if that string isnull .static booleanChecks if a string ends with the specified character.static booleanChecks if a string ends with the specified string.static booleanendsWithAny(String s, char... c) Checks if a string ends with any of the specified characters.static booleanendsWithAny(String s, String... suffixes) Checks if a string ends with any of the specified strings.static booleanendsWithIgnoreCase(String str, String suffix) Checks if a string ends with a suffix, ignoring case.static doubleCalculates the entropy of a string.static booleanequalsIgnoreCase(Object a, Object b) Tests two objects for case-insensitive string equality.static booleanequalsIgnoreCase(String str1, String str2) Tests two strings for case-insensitive equality, but gracefully handles nulls.static StringescapeChars(String s, AsciiSet escaped) Escapes the specified characters in the string.static StringEscapes a string for safe inclusion in Java source code.static StringescapeHtml(String str) Escapes HTML entities in a string.static StringescapeRegex(String str) Escapes regex special characters in a string.static StringEscapes SQL string literals by doubling single quotes.static StringEscapes XML entities in a string.extractBetween(String str, String start, String end) Extracts all text segments between start and end markers.extractEmails(String str) Extracts all email addresses from a string.extractNumbers(String str) Extracts all numeric sequences from a string.extractUrls(String str) Extracts all URLs from a string.extractWords(String str) Extracts all words from a string.static String[]Filters a string array using the specified predicate.static charReturns the first character in the specified string.static StringfirstNonBlank(String... vals) Returns the first non-blank string in the array.static StringfirstNonEmpty(String... s) Returns the first non-null, non-empty string in the list.static charReturns the first non-whitespace character in the string.static StringURL-encodes invalid characters in a URI string.static StringFormats a string using printf-style and/or MessageFormat-style format specifiers.static StringformatNamed(String s, Map<String, Object> m) Simple utility for replacing variables of the form"{key}" with values in the specified map.static byte[]Converts a hexadecimal character string to a byte array.static StringfromHexToUTF8(String hex) Converts a hexadecimal byte stream (e.g. "34A5BC") into a UTF-8 encoded string.static byte[]fromSpacedHex(String hex) Same asfromHex(String)except expects spaces between the byte strings.static StringConverts a space-deliminted hexadecimal byte stream (e.g. "34 A5 BC") into a UTF-8 encoded string.static StringGenerates a random UUID string in standard format.static StringGiven an absolute URI, returns just the authority portion (e.g.static longParses a duration string.static PatternConverts a string containing glob-style wildcard characters to a regular expressionPattern.static PatterngetGlobMatchPattern(String s, int flags) Converts a string containing glob-style wildcard characters to a regular expressionPatternwith flags.static PatternConverts a string containing"*" meta characters with a regular expression pattern.static PatterngetMatchPattern(String s, int flags) Converts a string containing"*" meta characters with a regular expression pattern.static StringTakes in a string, splits it by lines, and then prepends each line with line numbers.static StringgetNumberedLines(String s, int start, int end) Same asgetNumberedLines(String)except only returns the specified lines.static longgetStringSize(String str) Calculates the approximate memory size of a string in bytes.static booleanChecks if a string has text (not null, not empty, and contains at least one non-whitespace character).static intSame asString.indexOf(int)except allows you to check for multiple characters.static intFinds the index of the first occurrence of a substring within a string.static intindexOfIgnoreCase(String str, String search) Finds the index of the first occurrence of a substring within a string, ignoring case.static StringInterns a string, returning the canonical representation.static Stringinterpolate(String template, Map<String, Object> variables) Interpolates variables in a template string using"${name}" syntax.static booleanEfficiently determines whether a URL is of the pattern "xxx://xxx"static booleanisAllNotBlank(CharSequence... values) Checks if all of the provided strings are not blank (not null, not empty, and not whitespace only).static booleanisAllNotEmpty(CharSequence... values) Checks if all of the provided strings are not empty (not null and not zero-length).static booleanChecks if a string contains only alphabetic characters (a-z, A-Z).static booleanisAlphaNumeric(String str) Checks if a string contains only alphanumeric characters (a-z, A-Z, 0-9).static booleanisAnyNotBlank(CharSequence... values) Checks if any of the provided strings are not blank (not null, not empty, and not whitespace only).static booleanisAnyNotEmpty(CharSequence... values) Checks if any of the provided strings are not empty (not null and not zero-length).static booleanisBlank(CharSequence str) Checks if a string is blank (null, empty, or whitespace only).static booleanisCreditCard(String str) Checks if a string is a valid credit card number using the Luhn algorithm.static booleanReturnstrue if the specified string is numeric.static booleanChecks if a string contains only digit characters (0-9).static booleanChecks if a string is a valid email address.static booleanChecks if a string is null or empty.static booleanisFirstNumberChar(char c) Returnstrue if the specified character is a valid first character for a number.static booleanReturnstrue if the specified string is a floating point number.static booleanisInterned(String str) Checks if a string is already interned.static booleanisNotBlank(CharSequence str) Checks if a string is not blank (not null, not empty, and not whitespace only).static booleanisNumberChar(char c) Returnstrue if the specified character is a valid number character.static booleanReturnstrue if this string can be parsed byparseNumber(String, Class).static booleanReturnstrue if the specified string is one of the specified values.static booleanisPhoneNumber(String str) Checks if a string is a valid phone number.static booleanReturnstrue if the specified string appears to be valid JSON.static booleanisProbablyJsonArray(Object o, boolean ignoreWhitespaceAndComments) Returnstrue if the specified string appears to be a JSON array.static booleanisProbablyJsonObject(Object o, boolean ignoreWhitespaceAndComments) Returnstrue if the specified string appears to be a JSON object.static booleanChecks if two strings are similar based on a similarity threshold.static booleanEfficiently determines whether a URL is of the pattern "xxx:/xxx".static booleanisValidDateFormat(String dateStr, String format) Validates if a date string matches the specified date format.static booleanisValidHostname(String hostname) Validates if a string is a valid hostname.static booleanValidates if a string is a valid IP address (IPv4 or IPv6).static booleanValidates if a string is a valid IPv6 address format (without network operations).static booleanisValidMacAddress(String mac) Validates if a string is a valid MAC address.static booleanisValidRegex(String regex) Validates if a string is a valid regular expression pattern.static booleanisValidTimeFormat(String timeStr, String format) Validates if a time string matches the specified time format.static booleanisWhitespace(int c) Checks if a character is whitespace.static booleanisWhitespace(String str) Checks if a string contains only whitespace characters.static Stringjoin(int[] tokens, char d) Join the specified tokens into a delimited string.static StringJoins an array of integers with a delimiter.static StringJoins the specified tokens into a delimited string.static StringBuilderjoin(Object[] tokens, char d, StringBuilder sb) Join the specified tokens into a delimited string and writes the output to the specified string builder.static StringJoin the specified tokens into a delimited string.static StringCombines values into a simple comma-delimited string.static Stringjoin(Collection<?> values) Combines collection values into a simple comma-delimited string.static Stringjoin(Collection<?> tokens, char d) Join the specified tokens into a delimited string.static Stringjoin(Collection<?> tokens, String d) Join the specified tokens into a delimited string.static StringBuilderjoin(Collection<?> tokens, String d, StringBuilder sb) Joins the specified tokens into a delimited string and writes the output to the specified string builder.static StringSame asjoin(Collection, char)but escapes the delimiter if found in the tokens.static StringJoins tokens with newlines.static StringConverts a string to kebab-case format.static intlastIndexOf(String str, String search) Finds the index of the last occurrence of a substring within a string.static intlastIndexOfIgnoreCase(String str, String search) Finds the index of the last occurrence of a substring within a string, ignoring case.static charReturns the last non-whitespace character in the string.static StringReturns the leftmost characters of a string.static intlevenshteinDistance(String str1, String str2) Calculates the Levenshtein distance (edit distance) between two strings.static intCounts the number of lines in a string.static StringNull-safe convenience method forString.toLowerCase().static String[]Maps each element of a string array using the specified function.static booleanChecks if a string matches a regular expression pattern.static StringGenerates a Metaphone code for a string.static StringReturns the middle characters of a string.static charmostFrequentChar(String str) Finds the most frequent character in a string.static intnaturalCompare(String str1, String str2) Performs natural string comparison that handles numbers correctly.static StringnormalizeUnicode(String str) Normalizes Unicode characters in a string.static StringNormalizes all whitespace in a string to single spaces.static booleannotContains(String s, char c) Checks if a string does not contain the specified character.static booleannotContains(String s, CharSequence substring) Checks if a string does not contain the specified substring.static booleannotContains(String s, String substring) Checks if a string does not contain the specified substring.static booleannotContainsAll(String s, char... values) Checks if a string does not contain all of the specified characters.static booleannotContainsAll(String s, CharSequence... values) Checks if a string does not contain all of the specified substrings.static booleannotContainsAll(String s, String... values) Checks if a string does not contain all of the specified substrings.static booleannotContainsAny(String s, char... values) Checks if a string does not contain any of the specified characters.static booleannotContainsAny(String s, CharSequence... values) Checks if a string does not contain any of the specified substrings.static booleannotContainsAny(String s, String... values) Checks if a string does not contain any of the specified substrings.static StringReturns an obfuscated version of the specified string.static Stringordinal(int number) Converts a number to its ordinal form (1st, 2nd, 3rd, 4th, etc.).static StringCenter pads a string with a specified character.static StringLeft pads a string with a specified character.static StringRight pads a string with a specified character.static CharacterConverts aString to aCharacter static floatparseFloat(String value) Same asFloat.parseFloat(String)but removes any underscore characters first.static intSame asInteger.parseInt(String)but removes any underscore characters first.static intConverts a string containing a possible multiplier suffix to an integer.static longSame asLong.parseLong(String)but removes any underscore characters first.static longConverts a string containing a possible multiplier suffix to a long.Parses a string containing key-value pairs into a map.static NumberparseNumber(String s, Class<? extends Number> type) Parses a number from the specified string.static StringpascalCase(String str) Converts a string to PascalCase format.static StringPluralizes a word based on a count.static Stringrandom(int numchars) Generated a random UUID with the specified number of characters.static StringrandomAlphabetic(int length) Generates a random alphabetic string of the specified length.static StringrandomAlphanumeric(int length) Generates a random alphanumeric string of the specified length.static StringrandomAscii(int length) Generates a random ASCII string of the specified length.static StringrandomNumeric(int length) Generates a random numeric string of the specified length.static StringrandomString(int length, String chars) Generates a random string of the specified length using characters from the given character set.static doublereadabilityScore(String str) Calculates a simple readability score for a string.static StringConverts an arbitrary object to a readable string format suitable for debugging and testing.static StringRemoves all occurrences of a substring from a string.static StringremoveAccents(String str) Removes diacritical marks (accents) from characters in a string.static StringRemoves multiple substrings from a string.static StringremoveControlChars(String str) Removes control characters from a string, replacing them with spaces.static StringRemoves a suffix from a string if present.static StringremoveNonPrintable(String str) Removes non-printable characters from a string.static StringremoveStart(String str, String prefix) Removes a prefix from a string if present.static StringremoveUnderscores(String value) Removes all underscore characters from a string.static StringCreates a repeated pattern.static StringReplaces"\\uXXXX" character sequences with their unicode characters.static StringReverses a string.static StringReturns the rightmost characters of a string.static StringBasic HTML/XML sanitization - removes or escapes potentially dangerous content.static doublesimilarity(String str1, String str2) Calculates the similarity percentage between two strings using Levenshtein distance.static voidSkips over a single comment sequence in a StringReader.static StringConverts a string to snake_case format.static String[]Sorts a string array in natural order.static String[]sortIgnoreCase(String[] array) Sorts a string array in case-insensitive order.static StringGenerates a Soundex code for a string.Splits a comma-delimited list into a list of strings.Splits a character-delimited string into a string array.Same assplita(java.lang.String)but limits the number of tokens returned.static voidSame assplita(java.lang.String)but consumes the tokens instead of creating an array.static voidSame assplita(java.lang.String)but consumes the tokens instead of creating an array.static String[]Splits a comma-delimited list into an array of strings.static String[]Same assplita(String, char)except splits all strings in the input and returns a single result.static String[]Splits a character-delimited string into a string array.static String[]Same assplita(String, char)but limits the number of tokens returned.Splits a list of key-value pairs into an ordered map.static String[]Splits the method arguments in the signature of a method.Splits a comma-delimited list containing "nesting constructs".Splits a nested comma-delimited list.static String[]Splits a space-delimited string with optionally quoted arguments.static String[]splitQuoted(String s, boolean keepQuotes) Same assplitQuoted(String)but allows you to optionally keep the quote characters.static booleanstartsWith(String s, char c) An efficient method for checking if a string starts with a character.static booleanstartsWithIgnoreCase(String str, String prefix) Checks if a string starts with a prefix, ignoring case.stringSupplier(Supplier<?> s) Takes a supplier of any type and returns aSupplier<String>.static StringStrips the first and last character from a string.static StringStrips invalid characters such as CTRL characters from a string meant to be encoded as an HTTP header value.static StringsubstringAfter(String str, String separator) Returns the substring after the first occurrence of a separator.static StringsubstringBefore(String str, String separator) Returns the substring before the first occurrence of a separator.static StringsubstringBetween(String str, String open, String close) Returns the substring between two delimiters.static StringSwaps the case of all characters in a string.static StringConverts a string to Title Case format (first letter of each word capitalized, separated by spaces).static StringConverts the specified object to a comma-delimited list.static StringtoHex(byte b) Converts the specified byte into a 2 hexadecimal characters.static StringtoHex(byte[] bytes) Converts a byte array into a simple hexadecimal character string.static StringtoHex(InputStream is) Converts the contents of the specified input stream to a hex string.static char[]toHex2(int num) Converts the specified number into a 2 hexadecimal characters.static char[]toHex4(int num) Converts the specified number into a 4 hexadecimal characters.static char[]toHex8(long num) Converts the specified number into a 8 hexadecimal characters.static StringConverts the specified object to an ISO8601 date string.static StringConverts the specified object to an ISO8601 date-time string.static StringtoReadableBytes(byte[] b) Converts the specified bytes into a readable string.static StringtoSpacedHex(byte[] bytes) Same astoHex(byte[])but puts spaces between the byte strings.static StringSafely converts an object to a string, returningnull if the object isnull .static StringSafely converts an object to a string, returning the default string if the object isnull .static String[]toStringArray(Collection<String> collection) Converts a collection of strings to a string array.static URIConverts the specified object to a URI.static StringtoUtf8(byte[] b) Converts the specified byte array to a UTF-8 string.static StringtoUtf8(InputStream is) Converts the contents of the specified input stream to a UTF-8 string.static Stringtransliterate(String str, String fromChars, String toChars) Transliterates characters in a string by mapping characters from one set to another.static StringSame asString.trim()but preventsNullPointerExceptions .static StringTrims whitespace characters from the end of the specified string.static StringTrims'/' characters from the beginning of the specified string.static StringTrims'/' characters from both the start and end of the specified string.static StringTrims'/' and space characters from both the start and end of the specified string.static StringTrims whitespace characters from the beginning of the specified string.static StringTrims'/' characters from the end of the specified string.static Stringuncapitalize(String str) Uncapitalizes the first character of a string.static StringunescapeChars(String s, AsciiSet escaped) Removes escape characters from the specified characters.static StringunescapeHtml(String str) Unescapes HTML entities in a string.static StringunescapeXml(String str) Unescapes XML entities in a string.static StringunicodeSequence(char c) Creates an escaped-unicode sequence (e.g.static StringNull-safe convenience method forString.toUpperCase().static StringDecodes aapplication/x-www-form-urlencoded string usingUTF-8 encoding scheme.static StringEncodes aapplication/x-www-form-urlencoded string usingUTF-8 encoding scheme.static StringSame asurlEncode(String)except only escapes characters that absolutely need to be escaped.static StringSimilar toURLEncoder.encode(String, String)but doesn't encode"/" characters.static intCounts the number of words in a string.static StringWraps text to a specified line length.static StringWraps text to a specified line length with a custom newline string.
-
Field Details
-
COMMON_SEPARATORS
Characters considered common separators (comma/semicolon/colon/pipe/tab). -
CRLF
Windows-style carriage-return/line-feed sequence.- See Also:
-
DECIMAL_CHARS
Digits 0-9 represented as anAsciiSet. -
DIGIT
Digits 0-9 represented as anAsciiSet. -
EMPTY
Zero-length string constant.- See Also:
-
FIRST_NUMBER_CHARS
Characters allowed at the beginning of a numeric literal. -
HEXADECIMAL_CHARS
Hexadecimal digit characters. -
HTTP_HEADER_CHARS
Characters allowed in HTTP headers (including quoted strings and comments). -
LETTER
Letters a-z and A-Z represented as anAsciiSet. -
LETTER_LC
Lowercase letters a-z represented as anAsciiSet. -
LETTER_UC
Uppercase letters A-Z represented as anAsciiSet. -
MAP_ESCAPE_SET
Characters escaped when parsing key/value pairs. -
NEWLINE
Unix-style newline character.- See Also:
-
NOT_EMPTY
Predicate that filters outnulland empty strings. -
NUMBER_CHARS
Characters that can appear anywhere in a numeric literal. -
OCTAL_CHARS
Octal digit characters. -
QUOTE_ESCAPE_SET
Characters escaped when parsing quoted strings. -
SPACE
Single-space character constant.- See Also:
-
TAB
Horizontal tab character constant.- See Also:
-
URI_CHARS
Characters considered part of a URI when encoding paths. -
URL_ENCODE_PATHINFO_VALIDCHARS
Characters that may appear unescaped in path segments when URL-encoding. -
URL_UNENCODED_CHARS
Characters that never require URL encoding per RFC 3986. -
URL_UNENCODED_LAX_CHARS
Extended set of characters that are typically safe to leave unencoded. -
VOWEL
Vowel characters a, e, i, o, u (both uppercase and lowercase) represented as anAsciiSet. -
WHITESPACE_CHARS
All standard whitespace characters (space, tab, newline, carriage return, form feed, vertical tab). -
FP_REGEX
Floating-point literal validation pattern used byDouble.valueOf(String).Matches decimal, hexadecimal, and scientific-notation literals, as well as
NaNandInfinity, with optional sign, exponent, and type suffixes. Copied from the JDK source to keep parsing logic consistent.
-
-
Constructor Details
-
StringUtils
protected StringUtils()Constructor.
-
-
Method Details
-
abbreviate
Abbreviates a string using ellipses if it exceeds the specified length.If the string is longer than the specified length, it is truncated and
"..." is appended. The total length of the result will be exactlylength characters (including the ellipses).If the string is
null , shorter than or equal tolength , or has length 3 or less, the original string is returned unchanged.Example:
abbreviate(
"Hello World" , 8);// "Hello..." abbreviate("Hello World" , 20);// "Hello World" (no change) abbreviate("Hi" , 5);// "Hi" (too short to abbreviate) abbreviate(null , 10);// null - Parameters:
in- The input string. Can benull .length- The maximum length of the resulting string (must be at least 4 for abbreviation to occur).- Returns:
- The abbreviated string with ellipses, or the original string if no abbreviation is needed.
-
append
Appends a string to a StringBuilder, creating a new one if null.- Parameters:
sb- The StringBuilder to append to, ornull to create a new one.in- The string to append.- Returns:
- The StringBuilder with the string appended.
-
appendIfNotBlank
Appends a string to a StringBuilder if the string is not blank.Returns the same StringBuilder instance for method chaining. If the string is
null , empty, or contains only whitespace, nothing is appended. Ifsb isnull and an append is going to occur, a new StringBuilder is automatically created.Examples:
StringBuilder
sb =new StringBuilder(); appendIfNotBlank(sb ,"hello" );// Appends "hello" appendIfNotBlank(sb ," " );// Does nothing appendIfNotBlank(sb ,null );// Does nothing appendIfNotBlank(sb ,"world" );// Appends "world" // Result: "helloworld" // Auto-create StringBuilder if null and append occurs StringBuildersb2 = appendIfNotBlank(null ,"test" );// Creates new StringBuilder with "test" StringBuildersb3 = appendIfNotBlank(null ," " );// Returns null (no append occurred) - Parameters:
sb- The StringBuilder to append to. Can benull .str- The string to append if not blank. Can benull .- Returns:
- The same StringBuilder instance for method chaining, or a new StringBuilder if
sb wasnull and an append occurred, ornull ifsb wasnull and no append occurred.
-
appendIfNotEmpty
Appends a string to a StringBuilder if the string is not empty.Returns the same StringBuilder instance for method chaining. If the string is
null or empty, nothing is appended. Ifsb isnull and an append is going to occur, a new StringBuilder is automatically created.Examples:
StringBuilder
sb =new StringBuilder(); appendIfNotEmpty(sb ,"hello" );// Appends "hello" appendIfNotEmpty(sb ,"" );// Does nothing appendIfNotEmpty(sb ,null );// Does nothing appendIfNotEmpty(sb ,"world" );// Appends "world" // Result: "helloworld" // Auto-create StringBuilder if null and append occurs StringBuildersb2 = appendIfNotEmpty(null ,"test" );// Creates new StringBuilder with "test" StringBuildersb3 = appendIfNotEmpty(null ,null );// Returns null (no append occurred) - Parameters:
sb- The StringBuilder to append to. Can benull .str- The string to append if not empty. Can benull .- Returns:
- The same StringBuilder instance for method chaining, or a new StringBuilder if
sb wasnull and an append occurred, ornull ifsb wasnull and no append occurred.
-
appendWithSeparator
Appends a string to a StringBuilder with a separator, only adding the separator if the StringBuilder is not empty.Returns the same StringBuilder instance for method chaining. If the StringBuilder is empty, only the string is appended (no separator). If the StringBuilder is not empty, the separator is appended first, then the string. If
sb isnull and an append is going to occur, a new StringBuilder is automatically created.Examples:
StringBuilder
sb =new StringBuilder(); appendWithSeparator(sb ,"first" ,", " );// Appends "first" appendWithSeparator(sb ,"second" ,", " );// Appends ", second" appendWithSeparator(sb ,"third" ,", " );// Appends ", third" // Result: "first, second, third" // Auto-create StringBuilder if null and append occurs StringBuildersb2 = appendWithSeparator(null ,"test" ,", " );// Creates new StringBuilder with "test" StringBuildersb3 = appendWithSeparator(null ,null ,", " );// Returns null (no append occurred) - Parameters:
sb- The StringBuilder to append to. Can benull .str- The string to append. Can benull .separator- The separator to add before the string if the StringBuilder is not empty. Can benull .- Returns:
- The same StringBuilder instance for method chaining, or a new StringBuilder if
sb wasnull and an append occurred, ornull ifsb wasnull and no append occurred.
-
articlized
Adds the appropriate indefinite article ('a' or 'an') before a word.Uses a simple vowel-based rule: 'an' if the word starts with a vowel, 'a' otherwise.
- Parameters:
subject- The word to articlize.- Returns:
- The word with 'a' or 'an' prepended.
-
base64Decode
BASE64-decodes the specified string.- Parameters:
in- The BASE-64 encoded string.- Returns:
- The decoded byte array, or null if the input was
null .
-
base64DecodeToString
Shortcut for callingbase64Decode(String) and converting the result to a UTF-8 encoded string.- Parameters:
in- The BASE-64 encoded string to decode.- Returns:
- The decoded string.
-
base64Encode
BASE64-encodes the specified byte array.- Parameters:
in- The input byte array to convert.- Returns:
- The byte array converted to a BASE-64 encoded string.
-
base64EncodeToString
Shortcut for callingbase64Encode(in.getBytes("UTF-8" ))- Parameters:
in- The input string to convert.- Returns:
- The string converted to BASE-64 encoding.
-
buildString
Builds a string using a functional approach with a StringBuilder.Creates a new StringBuilder, applies the consumer to it, and returns the resulting string. This provides a functional way to build strings without manually managing the StringBuilder.
Examples:
String
result = buildString(sb -> {sb .append("Hello" );sb .append(" " );sb .append("World" ); });// Returns: "Hello World" Stringjoined = buildString(sb -> { appendWithSeparator(sb ,"a" ,", " ); appendWithSeparator(sb ,"b" ,", " ); appendWithSeparator(sb ,"c" ,", " ); });// Returns: "a, b, c" - Parameters:
builder- The consumer that builds the string using the provided StringBuilder.- Returns:
- The built string.
- Throws:
IllegalArgumentException- Ifbuilder isnull .
-
camelCase
Converts a string to camelCase format.Handles various input formats:
- Space-separated: "hello world" → "helloWorld"
- Underscore-separated: "hello_world" → "helloWorld"
- Hyphen-separated: "hello-world" → "helloWorld"
- PascalCase: "HelloWorld" → "helloWorld"
- Already camelCase: "helloWorld" → "helloWorld"
- Mixed case: "Hello_World-Test" → "helloWorldTest"
Example:
camelCase(
null );// null camelCase("" );// "" camelCase("hello world" );// "helloWorld" camelCase("hello_world" );// "helloWorld" camelCase("hello-world" );// "helloWorld" camelCase("HelloWorld" );// "helloWorld" camelCase("helloWorld" );// "helloWorld" camelCase(" hello world " );// "helloWorld" - Parameters:
str- The string to convert.- Returns:
- The camelCase string, or
null if input isnull .
-
capitalize
Capitalizes the first character of a string.Example:
capitalize(
null );// null capitalize("" );// "" capitalize("hello" );// "Hello" capitalize("Hello" );// "Hello" capitalize("HELLO" );// "HELLO" - Parameters:
str- The string to capitalize.- Returns:
- The string with the first character capitalized, or
null if input isnull .
-
cdlToList
Converts a comma-delimited string to a list.- Parameters:
s- The comma-delimited string.- Returns:
- A new modifiable list. Never
null .
-
cdlToSet
Converts a comma-delimited string to a set.- Parameters:
s- The comma-delimited string.- Returns:
- A new
LinkedHashSet. Nevernull .
-
charAt
Returns the character at the specified index in the string without throwing exceptions.This is a null-safe and bounds-safe version of
String.charAt(int). Returns0 (null character) if:- The string is
null - The index is negative
- The index is greater than or equal to the string length
Example:
charAt(
"Hello" , 0);// 'H' charAt("Hello" , 4);// 'o' charAt("Hello" , 5);// 0 (out of bounds) charAt("Hello" , -1);// 0 (out of bounds) charAt(null , 0);// 0 (null string) - Parameters:
s- The string.i- The index position.- Returns:
- The character at the specified index, or
0 if the index is out-of-range or the string isnull . - See Also:
- The string is
-
clean
Cleans a string by removing control characters and normalizing whitespace.Example:
clean(
"hello world" );// "hello world" clean("hello \t\n world" );// "hello world" - Parameters:
str- The string to clean.- Returns:
- The cleaned string, or
null if input isnull .
-
compare
Compares two strings lexicographically, but gracefully handlesnull values.Null handling:
- Both
null → returns0 (equal) - First
null → returnsInteger.MIN_VALUE - Second
null → returnsInteger.MAX_VALUE - Neither
null → returns the same asString.compareTo(String)
Example:
compare(
"apple" ,"banana" );// negative (apple < banana) compare("banana" ,"apple" );// positive (banana > apple) compare("apple" ,"apple" );// 0 (equal) compare(null ,null );// 0 (equal) compare(null ,"apple" );// Integer.MIN_VALUE compare("apple" ,null );// Integer.MAX_VALUE - Parameters:
s1- The first string.s2- The second string.- Returns:
- A negative integer, zero, or a positive integer as the first string is less than, equal to, or greater than the second.
- See Also:
- Both
-
compareIgnoreCase
Compares two strings lexicographically, ignoring case.Returns a negative integer, zero, or a positive integer as the first string is less than, equal to, or greater than the second string, ignoring case.
Example:
compareIgnoreCase(
"apple" ,"BANANA" );// negative (apple < banana) compareIgnoreCase("Hello" ,"hello" );// 0 (equal) compareIgnoreCase("Zebra" ,"apple" );// positive (zebra > apple) - Parameters:
str1- The first string.str2- The second string.- Returns:
- A negative integer, zero, or a positive integer as the first string is less than, equal to, or greater than the second.
-
compress
Compresses a UTF-8 string into a GZIP-compressed byte array.This method compresses the input string using GZIP compression. The string is first converted to UTF-8 bytes, then compressed. Use
decompress(byte[])to decompress the result.Example:
// Compress a string byte[]compressed = compress("Hello World" );// Decompress it back Stringdecompressed = decompress(compressed );// Returns: "Hello World" - Parameters:
contents- The UTF-8 string to compress.- Returns:
- The GZIP-compressed byte array.
- Throws:
Exception- If compression fails.- See Also:
-
contains
Checks if a string contains the specified character.This is a null-safe operation. Returns
false if the string isnull .Example:
contains(
"Hello World" ,'o' );// true contains("Hello World" ,'x' );// false contains(null ,'a' );// false - Parameters:
s- The string to check.c- The character to check for.- Returns:
true if the string contains the specified character.- See Also:
-
contains
Null-safeString.contains(CharSequence)operation.Returns
false if the string isnull , otherwise behaves the same asString.contains(CharSequence).Example:
contains(
"Hello World" ,"World" );// true contains("Hello World" ,"Foo" );// false contains(null ,"Hello" );// false - Parameters:
value- The string to check.substring- The substring to check for.- Returns:
true if the value contains the specified substring,false if the string isnull .- See Also:
-
contains
Null-safe check if a string contains another string.Returns
false if the string isnull , otherwise behaves the same asString.contains(CharSequence).Example:
contains(
"Hello World" ,"World" );// true contains("Hello World" ,"Foo" );// false contains(null ,"Hello" );// false - Parameters:
s- The string to check.substring- The substring to check for.- Returns:
true if the string contains the specified substring,false if the string isnull .- See Also:
-
containsAll
Checks if a string contains all of the specified characters.This is a null-safe operation that returns
false if:- The string is
null - The values array is
null or empty - Any of the specified characters are not found in the string
Example:
containsAll(
"Hello World" ,'H' ,'e' ,'l' );// true (contains all) containsAll("Hello World" ,'H' ,'x' );// false (missing 'x') containsAll(null ,'a' );// false - Parameters:
s- The string to check.values- The characters to check for.- Returns:
true if the string contains all of the specified characters.- See Also:
- The string is
-
containsAll
Checks if a string contains all of the specified substrings.This is a null-safe operation that returns
false if:- The string is
null - The values array is
null or empty - Any of the specified substrings are not found in the string
Example:
containsAll(
"Hello World" ,"Hello" ,"World" );// true (contains all) containsAll("Hello World" ,"Hello" ,"Foo" );// false (missing "Foo") containsAll(null ,"Hello" );// false - Parameters:
s- The string to check.values- The substrings to check for.- Returns:
true if the string contains all of the specified substrings.- See Also:
- The string is
-
containsAll
Checks if a string contains all of the specified substrings.This is a null-safe operation that returns
false if:- The string is
null - The values array is
null or empty - Any of the specified substrings are not found in the string
Example:
containsAll(
"Hello World" ,"Hello" ,"World" );// true (contains all) containsAll("Hello World" ,"Hello" ,"Foo" );// false (missing "Foo") containsAll(null ,"Hello" );// false - Parameters:
s- The string to check.values- The substrings to check for.- Returns:
true if the string contains all of the specified substrings.- See Also:
- The string is
-
containsAny
Checks if a string contains any of the specified characters.This is a null-safe operation that returns
false if:- The string is
null - The values array is
null or empty - None of the specified characters are found in the string
Example:
containsAny(
"Hello World" ,'o' ,'x' );// true (contains 'o') containsAny("Hello World" ,'x' ,'y' );// false containsAny(null ,'a' );// false - Parameters:
s- The string to check.values- The characters to check for.- Returns:
true if the string contains any of the specified characters.- See Also:
- The string is
-
containsAny
Checks if a string contains any of the specified substrings.This is a null-safe operation that returns
false if:- The string is
null - The values array is
null or empty - None of the specified substrings are found in the string
Example:
containsAny(
"Hello World" ,"Hello" ,"Foo" );// true (contains "Hello") containsAny("Hello World" ,"Foo" ,"Bar" );// false containsAny(null ,"Hello" );// false - Parameters:
s- The string to check.values- The substrings to check for.- Returns:
true if the string contains any of the specified substrings.- See Also:
- The string is
-
containsAny
Checks if a string contains any of the specified substrings.This is a null-safe operation that returns
false if:- The string is
null - The values array is
null or empty - None of the specified substrings are found in the string
Example:
containsAny(
"Hello World" ,"Hello" ,"Foo" );// true (contains "Hello") containsAny("Hello World" ,"Foo" ,"Bar" );// false containsAny(null ,"Hello" );// false containsAny("Hello" );// false (no values to check) - Parameters:
s- The string to check.values- The substrings to check for.- Returns:
true if the string contains any of the specified substrings.- See Also:
- The string is
-
containsIgnoreCase
Checks if a string contains a substring, ignoring case.Example:
containsIgnoreCase(
"Hello World" ,"world" );// true containsIgnoreCase("Hello World" ,"WORLD" );// true containsIgnoreCase("hello world" ,"xyz" );// false - Parameters:
str- The string to search in.search- The substring to search for.- Returns:
true if the string contains the substring (ignoring case),false otherwise.
-
countChars
Counts the number of occurrences of the specified character in the specified string.Returns
0 if the string isnull .Example:
countChars(
"Hello World" ,'o' );// 2 countChars("Hello World" ,'x' );// 0 countChars(null ,'a' );// 0 - Parameters:
s- The string to check.c- The character to count.- Returns:
- The number of occurrences of the character, or
0 if the string wasnull .
-
countMatches
Counts the number of occurrences of a substring within a string.Example:
countMatches(
"hello world world" ,"world" );// 2 countMatches("ababab" ,"ab" );// 3 countMatches("hello" ,"xyz" );// 0 - Parameters:
str- The string to search in.search- The substring to count.- Returns:
- The number of occurrences, or
0 if not found or if either parameter isnull or empty.
-
decodeHex
Debug method for rendering non-ASCII character sequences.Converts non-printable and non-ASCII characters (outside the range
0x20-0x7E ) to hexadecimal sequences in the format"[hex]" . Printable ASCII characters are left unchanged.Example:
decodeHex(
"Hello" );// "Hello" decodeHex("Hello World" );// "Hello[0]World" decodeHex("Hello©" );// "Hello[a9]" decodeHex(null );// null - Parameters:
s- The string to decode.- Returns:
- A string with non-ASCII characters converted to
"[hex]" sequences, ornull if input isnull .
-
decompress
Decompresses a GZIP-compressed byte array into a UTF-8 string.This method is the inverse of
compress(String). It takes a byte array that was compressed using GZIP compression and decompresses it into a UTF-8 encoded string.Example:
// Compress a string byte[]compressed = compress("Hello World" );// Decompress it back Stringdecompressed = decompress(compressed );// Returns: "Hello World" - Parameters:
is- The GZIP-compressed byte array to decompress.- Returns:
- The decompressed UTF-8 string.
- Throws:
Exception- If decompression fails or the input is not valid GZIP data.- See Also:
-
defaultIfBlank
Returns the specified string, or the default string if that string isnull or blank.- Parameters:
str- The string value to check.defaultStr- The default string to return if the string isnull or blank.- Returns:
- The string value, or the default string if the string is
null or blank.
-
defaultIfEmpty
Returns the specified string, or the default string if that string isnull or empty.- Parameters:
str- The string value to check.defaultStr- The default string to return if the string isnull or empty.- Returns:
- The string value, or the default string if the string is
null or empty.
-
diffPosition
Finds the position where the two strings first differ.This method compares strings character by character and returns the index of the first position where they differ. If the strings are equal, returns
-1 . If one string is a prefix of the other, returns the length of the shorter string.Example:
diffPosition(
"apple" ,"apple" );// -1 (equal) diffPosition("apple" ,"apricot" );// 2 (differs at 'p' vs 'r') diffPosition("apple" ,"app" );// 3 (shorter string ends here) diffPosition("app" ,"apple" );// 3 (shorter string ends here) - Parameters:
s1- The first string.s2- The second string.- Returns:
- The position where the two strings differ, or
-1 if they're equal. - See Also:
-
diffPositionIc
Finds the position where the two strings first differ, ignoring case.This method compares strings character by character (case-insensitive) and returns the index of the first position where they differ. If the strings are equal (ignoring case), returns
-1 . If one string is a prefix of the other, returns the length of the shorter string.Example:
diffPositionIc(
"Apple" ,"apple" );// -1 (equal ignoring case) diffPositionIc("Apple" ,"Apricot" );// 2 (differs at 'p' vs 'r') diffPositionIc("APPLE" ,"app" );// 3 (shorter string ends here) - Parameters:
s1- The first string.s2- The second string.- Returns:
- The position where the two strings differ, or
-1 if they're equal (ignoring case). - See Also:
-
distinct
Removes duplicate elements from a string array, preserving order.Returns
null if the array isnull . Uses aLinkedHashSetto preserve insertion order while removing duplicates.Examples:
String[]
array = {"foo" ,"bar" ,"foo" ,"baz" ,"bar" }; String[]unique = distinct(array );// Returns: ["foo", "bar", "baz"] - Parameters:
array- The array to process. Can benull .- Returns:
- A new array with duplicate elements removed, or
null if the array wasnull .
-
doubleMetaphone
Generates a Double Metaphone code for a string.Double Metaphone is an improved version of Metaphone that returns two codes: a primary code and an alternate code. This handles more edge cases and variations.
Example:
doubleMetaphone(
"Smith" );// "SM0" doubleMetaphone("Schmidt" );// "XMT" - Parameters:
str- The string to generate a Double Metaphone code for. Can benull .- Returns:
- An array with two elements: [primary code, alternate code]. Returns
null if input isnull or empty.
-
emptyIfNull
Returns the specified string, or an empty string if that string isnull .- Parameters:
str- The string value to check.- Returns:
- The string value, or an empty string if the string is
null .
-
endsWith
Checks if a string ends with the specified character.This is a null-safe operation. Returns
false if the string isnull or empty.Example:
endsWith(
"Hello" ,'o' );// true endsWith("Hello" ,'H' );// false endsWith(null ,'o' );// false endsWith("" ,'o' );// false - Parameters:
s- The string to check. Can benull .c- The character to check for.- Returns:
true if the specified string is notnull and ends with the specified character.- See Also:
-
endsWith
Checks if a string ends with the specified string.This is a null-safe operation. Returns
false if the string isnull . Otherwise behaves the same asString.endsWith(String).Example:
endsWith(
"Hello World" ,"World" );// true endsWith("Hello World" ,"Hello" );// false endsWith(null ,"World" );// false - Parameters:
s- The string to check. Can benull .suffix- The suffix to check for.- Returns:
true if the string ends with the specified suffix.- See Also:
-
endsWithAny
Checks if a string ends with any of the specified characters.This is a null-safe operation. Returns
false if:- The string is
null or empty - The characters array is
null or empty - The string does not end with any of the specified characters
Example:
endsWithAny(
"Hello" ,'o' ,'x' );// true (ends with 'o') endsWithAny("Hello" ,'x' ,'y' );// false endsWithAny(null ,'o' );// false - Parameters:
s- The string to check. Can benull .c- The characters to check for.- Returns:
true if the string ends with any of the specified characters.- See Also:
- The string is
-
endsWithAny
Checks if a string ends with any of the specified strings.This is a null-safe operation. Returns
false if:- The string is
null - The suffixes array is
null or empty - The string does not end with any of the specified suffixes
Example:
endsWithAny(
"Hello World" ,"World" ,"Foo" );// true (ends with "World") endsWithAny("Hello World" ,"Hello" ,"Foo" );// false endsWithAny(null ,"World" );// false - Parameters:
s- The string to check. Can benull .suffixes- The suffixes to check for.- Returns:
true if the string ends with any of the specified suffixes.- See Also:
- The string is
-
endsWithIgnoreCase
Checks if a string ends with a suffix, ignoring case.Example:
endsWithIgnoreCase(
"Hello World" ,"world" );// true endsWithIgnoreCase("Hello World" ,"WORLD" );// true endsWithIgnoreCase("hello world" ,"hello" );// false - Parameters:
str- The string to check.suffix- The suffix to check for.- Returns:
true if the string ends with the suffix (ignoring case),false otherwise.
-
entropy
Calculates the entropy of a string.Entropy measures the randomness or information content of a string. Higher entropy indicates more randomness. The formula used is:
H(X) = -Σ P(x) * log2(P(x)) where P(x) is the probability of character x.Example:
entropy(
"aaaa" );// 0.0 (no randomness) entropy("abcd" );// 2.0 (high randomness) entropy("hello" );// ~2.32 - Parameters:
str- The string to calculate entropy for. Can benull .- Returns:
- The entropy value (0.0 or higher), or
0.0 if the string isnull or empty.
-
equalsIgnoreCase
Tests two objects for case-insensitive string equality.Converts both objects to strings using
Object.toString()before comparison. This method handlesnull values gracefully:- Both
null → returnstrue - One
null → returnsfalse - Neither
null → compares string representations ignoring case
Example:
equalsIgnoreCase(
"Hello" ,"HELLO" );// true equalsIgnoreCase("Hello" ,"World" );// false equalsIgnoreCase(null ,null );// true equalsIgnoreCase("Hello" ,null );// false equalsIgnoreCase(123,"123" );// true (converts 123 to "123") - Parameters:
a- Object 1.b- Object 2.- Returns:
true if both objects are equal ignoring case.- See Also:
- Both
-
equalsIgnoreCase
Tests two strings for case-insensitive equality, but gracefully handles nulls.This method handles
null values gracefully:- Both
null → returnstrue (same reference check) - One
null → returnsfalse - Neither
null → compares strings ignoring case
Example:
equalsIgnoreCase(
"Hello" ,"hello" );// true equalsIgnoreCase("Hello" ,"WORLD" );// false equalsIgnoreCase(null ,null );// true equalsIgnoreCase("Hello" ,null );// false - Parameters:
str1- The first string.str2- The second string.- Returns:
true if the strings are equal ignoring case,false otherwise.- See Also:
- Both
-
escapeChars
Escapes the specified characters in the string.- Parameters:
s- The string with characters to escape.escaped- The characters to escape.- Returns:
- The string with characters escaped, or the same string if no escapable characters were found.
-
escapeForJava
Escapes a string for safe inclusion in Java source code.This method converts special characters to their Java escape sequences and converts non-printable ASCII characters to Unicode escape sequences.
Escape mappings:
"→\"\→\\\n→\\n\r→\\r\t→\\t\f→\\f\b→\\b- Non-printable characters →
\\uXXXX
Example:
var escaped =escapeForJava ("Hello\nWorld\"Test\"" );// Returns: "Hello\\nWorld\\\"Test\\\"" - Parameters:
s- The string to escape.- Returns:
- The escaped string safe for Java source code, or
null if input isnull .
-
escapeHtml
Escapes HTML entities in a string.Escapes the following characters:
'&' →"&" '<' →"<" '>' →">" '"' →""" '\'' →"'"
Example:
escapeHtml(
"<script>alert('xss')</script>" );// Returns: "<script>alert('xss')</script>" - Parameters:
str- The string to escape.- Returns:
- The escaped string, or
null if input isnull .
-
escapeRegex
Escapes regex special characters in a string.Escapes the following regex special characters:
\.*+?^${}()[]|\\ Example:
escapeRegex(
"file.txt" );// Returns: "file\\.txt" escapeRegex("price: $10.99" );// Returns: "price: \\$10\\.99" - Parameters:
str- The string to escape.- Returns:
- The escaped string, or
null if input isnull .
-
escapeSql
Escapes SQL string literals by doubling single quotes.Basic SQL escaping for string literals. Escapes single quotes by doubling them. This is a basic implementation - for production use, consider using prepared statements.
Example:
escapeSql(
"O'Brien" );// Returns: "O''Brien" escapeSql("It's a test" );// Returns: "It''s a test" - Parameters:
str- The string to escape.- Returns:
- The escaped string, or
null if input isnull .
-
escapeXml
Escapes XML entities in a string.Escapes the following characters:
'&' →"&" '<' →"<" '>' →">" '"' →""" '\'' →"'"
Example:
escapeXml(
"<tag attr='value'>text</tag>" );// Returns: "<tag attr='value'>text</tag>" - Parameters:
str- The string to escape.- Returns:
- The escaped string, or
null if input isnull .
-
extractBetween
Extracts all text segments between start and end markers.Finds all occurrences of text between the start and end markers (non-overlapping).
Example:
extractBetween(
"<tag>content</tag>" ,"<" ,">" );// ["tag", "/tag"] extractBetween("[one][two][three]" ,"[" ,"]" );// ["one", "two", "three"] - Parameters:
str- The string to extract from. Can benull .start- The start marker. Can benull .end- The end marker. Can benull .- Returns:
- A list of text segments found between the markers, or an empty list if any parameter is
null or empty.
-
extractEmails
Extracts all email addresses from a string.Uses a basic email regex pattern to find email addresses.
Example:
extractEmails(
"Contact: user@example.com or admin@test.org" );// ["user@example.com", "admin@test.org"] - Parameters:
str- The string to extract emails from. Can benull .- Returns:
- A list of email addresses found in the input, or an empty list if the string is
null or empty.
-
extractNumbers
Extracts all numeric sequences from a string.Finds all sequences of digits (including decimal numbers with dots).
Example:
extractNumbers(
"Price: $19.99, Quantity: 5" );// ["19.99", "5"] extractNumbers("Version 1.2.3" );// ["1.2", "3"] - Parameters:
str- The string to extract numbers from. Can benull .- Returns:
- A list of numeric strings found in the input, or an empty list if the string is
null or empty.
-
extractUrls
Extracts all URLs from a string.Uses a basic URL regex pattern to find URLs (http, https, ftp).
Example:
extractUrls(
"Visit https://example.com or http://test.org" );// ["https://example.com", "http://test.org"] - Parameters:
str- The string to extract URLs from. Can benull .- Returns:
- A list of URLs found in the input, or an empty list if the string is
null or empty.
-
extractWords
Extracts all words from a string.A word is defined as a sequence of letters, digits, and underscores.
Example:
extractWords(
"Hello world! This is a test." );// ["Hello", "world", "This", "is", "a", "test"] - Parameters:
str- The string to extract words from. Can benull .- Returns:
- A list of words found in the input, or an empty list if the string is
null or empty.
-
filter
Filters a string array using the specified predicate.Returns
null if the array isnull . Returns an empty array if the predicate isnull or no elements match.Examples:
String[]
array = {"foo" ,"" ,"bar" ,null ,"baz" }; String[]filtered = filter(array , StringUtils.NOT_EMPTY );// Returns: ["foo", "bar", "baz"] String[]longStrings = filter(array , s -> s !=null && s.length() > 3);// Returns: ["baz"] - Parameters:
array- The array to filter. Can benull .predicate- The predicate to apply to each element. Can benull .- Returns:
- A new array containing only the elements that match the predicate, or
null if the array wasnull .
-
firstChar
Returns the first character in the specified string.This is a null-safe and bounds-safe operation. Returns
0 (null character) if:- The string is
null - The string is empty
Example:
firstChar(
"Hello" );// 'H' firstChar("World" );// 'W' firstChar("" );// 0 (empty string) firstChar(null );// 0 (null string) - Parameters:
s- The string to check.- Returns:
- The first character in the string, or
0 if the string isnull or empty. - See Also:
- The string is
-
firstNonBlank
Returns the first non-blank string in the array.- Parameters:
vals- The strings to check.- Returns:
- The first non-blank string, or
null if all values were blank ornull .
-
firstNonEmpty
Returns the first non-null, non-empty string in the list.This method iterates through the provided strings and returns the first one that is not
null and not empty (as determined byUtils.ne(CharSequence)).Example:
firstNonEmpty(
null ,"" ,"Hello" ,"World" );// "Hello" firstNonEmpty("Hello" ,"World" );// "Hello" firstNonEmpty(null ,"" );// null firstNonEmpty();// null - Parameters:
s- The strings to test.- Returns:
- The first non-empty string in the list, or
null if they were allnull or empty. - See Also:
-
firstNonWhitespaceChar
Returns the first non-whitespace character in the string.This method scans the string from the beginning and returns the first character that is not a whitespace character (as determined by
Character.isWhitespace(char)).Example:
firstNonWhitespaceChar(
"Hello" );// 'H' firstNonWhitespaceChar(" Hello" );// 'H' firstNonWhitespaceChar("\t\nWorld" );// 'W' firstNonWhitespaceChar(" " );// 0 (only whitespace) firstNonWhitespaceChar(null );// 0 (null string) - Parameters:
s- The string to check.- Returns:
- The first non-whitespace character, or
0 if the string isnull , empty, or composed of only whitespace. - See Also:
-
fixUrl
URL-encodes invalid characters in a URI string.This method escapes characters that are not valid in URIs by converting them to percent-encoded format. Spaces are converted to
"+" characters, and other invalid characters are percent-encoded (e.g.,"hello world" becomes"hello+world" ).Only ASCII characters (0-127) that are not in the valid URI character set are encoded. If the string contains no invalid characters, the original string is returned.
Example:
fixUrl(
"hello world" );// "hello+world" fixUrl("file://path/to file.txt" );// "file://path/to+file.txt" fixUrl("valid-url" );// "valid-url" (no change) fixUrl(null );// null - Parameters:
in- The URI string to encode. Can benull .- Returns:
- The URI with invalid characters encoded, or
null if input isnull . - See Also:
-
format
Formats a string using printf-style and/or MessageFormat-style format specifiers.This method provides unified string formatting that supports both printf-style formatting (similar to C's
printf() function and Java'sString.format(String, Object...)) and MessageFormat-style formatting in the same pattern.Format Support:
- Printf-style:
"%s" ,"%d" ,"%.2f" ,"%1$s" , etc. - MessageFormat-style:
"{0}" ,"{1,number}" ,"{2,date}" , etc. - Un-numbered MessageFormat:
"{}" - Sequential placeholders that are automatically numbered - Mixed formats: Both styles can be used in the same pattern
Printf Format Specifiers:
- %s - String
- %d - Decimal integer
- %f - Floating point
- %x - Hexadecimal (lowercase)
- %X - Hexadecimal (uppercase)
- %o - Octal
- %b - Boolean
- %c - Character
- %e - Scientific notation (lowercase)
- %E - Scientific notation (uppercase)
- %g - General format (lowercase)
- %G - General format (uppercase)
- %n - Platform-specific line separator
- %% - Literal percent sign
Format Specifier Syntax:
Printf format specifiers follow this pattern:
%[argument_index$][flags][width][.precision]conversion MessageFormat placeholders follow this pattern:
{argument_index[,format_type[,format_style]]} Examples:
// Printf-style formatting format("Hello %s, you have %d items" ,"John" , 5);// Returns: "Hello John, you have 5 items" // Floating point with precision format("Price: $%.2f" , 19.99);// Returns: "Price: $19.99" // MessageFormat-style formatting format("Hello {0}, you have {1} items" ,"John" , 5);// Returns: "Hello John, you have 5 items" // Un-numbered MessageFormat placeholders (sequential) format("Hello {}, you have {} items" ,"John" , 5);// Returns: "Hello John, you have 5 items" // Mixed format styles in the same pattern format("User {0} has %d items and %s status" ,"Alice" , 10,"active" );// Returns: "User Alice has 10 items and active status" // Width and alignment (printf) format("Name: %-20s Age: %3d" ,"John" , 25);// Returns: "Name: John Age: 25" // Hexadecimal (printf) format("Color: #%06X" , 0xFF5733);// Returns: "Color: #FF5733" // Argument index (reuse arguments) format("%1$s loves %2$s, and {0} also loves %3$s" ,"Alice" ,"Bob" ,"Charlie" );// Returns: "Alice loves Bob, and Alice also loves Charlie" Comparison with mformat():
This method supports both MessageFormat-style and printf-style formats.
// Both styles supported (this method) format("Hello %s, you have %d items" ,"John" , 5); format("Hello {0}, you have {1} items" ,"John" , 5); format("User {0} has %d items" ,"Alice" , 10);// MessageFormat style only mformat("Hello {0}, you have {1} items" ,"John" , 5);Null Handling:
Null arguments are formatted as the string
"null" for string conversions, or cause aNullPointerExceptionfor numeric conversions (consistent withString.format(String, Object...)).- Parameters:
pattern- The format string supporting both MessageFormat and printf-style placeholders.args- The arguments to format.- Returns:
- The formatted string.
- Throws:
IllegalFormatException- If the format string is invalid or arguments don't match the format specifiers.- See Also:
- Printf-style:
-
formatNamed
Simple utility for replacing variables of the form"{key}" with values in the specified map.Supports named MessageFormat-style variables:
"{key}" wherekey is a map key. For un-numbered sequential placeholders"{}" , useformat(String, Object...)instead.Variable values are converted to strings using
readable(Object)to ensure consistent, readable formatting (e.g., byte arrays are converted to hex, collections are formatted without spaces).Nested variables are supported in both the input string and map values.
If the map does not contain the specified value, the variable is not replaced.
null values in the map are treated as blank strings.- Parameters:
s- The string containing variables to replace.m- The map containing the variable values.- Returns:
- The new string with variables replaced, or the original string if it didn't have variables in it.
-
fromHex
Converts a hexadecimal character string to a byte array.- Parameters:
hex- The string to convert to a byte array.- Returns:
- A new byte array.
-
fromHexToUTF8
Converts a hexadecimal byte stream (e.g. "34A5BC") into a UTF-8 encoded string.- Parameters:
hex- The hexadecimal string.- Returns:
- The UTF-8 string.
-
fromSpacedHex
Same asfromHex(String)except expects spaces between the byte strings.- Parameters:
hex- The string to convert to a byte array.- Returns:
- A new byte array.
-
fromSpacedHexToUTF8
Converts a space-deliminted hexadecimal byte stream (e.g. "34 A5 BC") into a UTF-8 encoded string.- Parameters:
hex- The hexadecimal string.- Returns:
- The UTF-8 string.
-
generateUUID
Generates a random UUID string in standard format.Returns a UUID in the format:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx Example:
generateUUID();
// "550e8400-e29b-41d4-a716-446655440000" - Returns:
- A new random UUID string.
-
getAuthorityUri
Given an absolute URI, returns just the authority portion (e.g."http://hostname:port" )- Parameters:
s- The URI string.- Returns:
- Just the authority portion of the URI.
-
getDuration
Parses a duration string.Supports simple duration formats:
Format Examples:
"1000" - 1000 milliseconds (no suffix)"10s" - 10 seconds"10 sec" - 10 seconds"10 seconds" - 10 seconds"1.5h" - 1.5 hours (5400000 ms)"1h30m" - 1 hour 30 minutes (5400000 ms)"1h 30m" - 1 hour 30 minutes (with spaces)
Supported Units:
- Milliseconds:
"ms" ,"millis" ,"milliseconds" (or no suffix) - Seconds:
"s" ,"sec" ,"second" ,"seconds" - Minutes:
"m" ,"min" ,"minute" ,"minutes" - Hours:
"h" ,"hour" ,"hours" - Days:
"d" ,"day" ,"days" - Weeks:
"w" ,"week" ,"weeks" - Months:
"mo" ,"month" ,"months" (30 days) - Years:
"y" ,"yr" ,"year" ,"years" (365 days)
Suffixes are case-insensitive.
Whitespace is ignored.
Decimal values are supported (e.g.,"1.5h" ).
Combined formats are supported (e.g.,"1h30m" ).- Parameters:
s- The string to parse.- Returns:
- The time in milliseconds, or
-1 if the string is empty ornull .
-
getGlobMatchPattern
Converts a string containing glob-style wildcard characters to a regular expressionPattern.This method converts glob-style patterns to regular expressions with the following mappings:
*matches any sequence of characters (including none)?matches exactly one character- All other characters are treated literally
Example:
var pattern =getGlobMatchPattern ("user_*_temp" );boolean matches =pattern .matcher("user_alice_temp" ).matches();// true matches =pattern .matcher("user_bob_temp" ).matches();// true matches =pattern .matcher("admin_alice_temp" ).matches();// false - Parameters:
s- The glob-style wildcard pattern string.- Returns:
- A compiled
Patternobject, ornull if the input string isnull .
-
getGlobMatchPattern
Converts a string containing glob-style wildcard characters to a regular expressionPatternwith flags.This method converts glob-style patterns to regular expressions with the following mappings:
*matches any sequence of characters (including none)?matches exactly one character- All other characters are treated literally
Example:
// Case-insensitive matching var pattern =getGlobMatchPattern ("USER_*" , Pattern.CASE_INSENSITIVE );boolean matches =pattern .matcher("user_alice" ).matches();// true -
getMatchPattern
Converts a string containing"*" meta characters with a regular expression pattern.- Parameters:
s- The string to create a pattern from.- Returns:
- A regular expression pattern.
-
getMatchPattern
Converts a string containing"*" meta characters with a regular expression pattern.- Parameters:
s- The string to create a pattern from.flags- Regular expression flags.- Returns:
- A regular expression pattern.
-
getNumberedLines
Takes in a string, splits it by lines, and then prepends each line with line numbers.- Parameters:
s- The string.- Returns:
- The string with line numbers added.
-
getNumberedLines
Same asgetNumberedLines(String)except only returns the specified lines.Out-of-bounds values are allowed and fixed.
- Parameters:
s- The string.start- The starting line (1-indexed).end- The ending line (1-indexed).- Returns:
- The string with line numbers added.
-
getStringSize
Calculates the approximate memory size of a string in bytes.Returns
0 if the input string isnull . This method provides an estimate based on typical JVM object layout:- String object overhead: ~24 bytes (object header + fields)
- char[] array overhead: ~16 bytes (array header)
- Character data: 2 bytes per character
Note: Actual memory usage may vary based on JVM implementation, object alignment, and whether compressed OOPs are enabled. This is an approximation for informational purposes.
Examples:
getStringSize(
null );// Returns: 0 getStringSize("" );// Returns: ~40 bytes getStringSize("hello" );// Returns: ~50 bytes (40 + 10) getStringSize("test" );// Returns: ~48 bytes (40 + 8) - Parameters:
str- The string to measure. Can benull .- Returns:
- The approximate memory size in bytes, or
0 if the input wasnull .
-
hasText
Checks if a string has text (not null, not empty, and contains at least one non-whitespace character).Example:
hasText(
null );// false hasText("" );// false hasText(" " );// false hasText("hello" );// true - Parameters:
str- The string to check.- Returns:
true if the string is not null, not empty, and contains at least one non-whitespace character.
-
indexOf
Same asString.indexOf(int)except allows you to check for multiple characters.- Parameters:
s- The string to check.c- The characters to check for.- Returns:
- The index into the string that is one of the specified characters.
-
indexOf
Finds the index of the first occurrence of a substring within a string.Example:
indexOf(
"hello world" ,"world" );// 6 indexOf("hello world" ,"xyz" );// -1 indexOf(null ,"test" );// -1 - Parameters:
str- The string to search in.search- The substring to search for.- Returns:
- The index of the first occurrence, or
-1 if not found or if either parameter isnull .
-
indexOfIgnoreCase
Finds the index of the first occurrence of a substring within a string, ignoring case.Example:
indexOfIgnoreCase(
"Hello World" ,"world" );// 6 indexOfIgnoreCase("Hello World" ,"WORLD" );// 6 indexOfIgnoreCase("hello world" ,"xyz" );// -1 - Parameters:
str- The string to search in.search- The substring to search for.- Returns:
- The index of the first occurrence, or
-1 if not found or if either parameter isnull .
-
intern
Interns a string, returning the canonical representation.Returns
null if the input string isnull . This method provides a null-safe wrapper aroundString.intern().Examples:
String
s1 =new String("test" ); Strings2 =new String("test" ); assertTrue(s1 !=s2 );// Different objects Stringi1 = intern(s1 ); Stringi2 = intern(s2 ); assertTrue(i1 ==i2 );// Same interned object Performance Note:
String interning stores strings in a special pool, which can save memory when the same string values are used repeatedly. However, the intern pool has limited size and interning can be slow, so use judiciously for strings that are known to be repeated frequently.
- Parameters:
str- The string to intern. Can benull .- Returns:
- The interned string, or
null if the input wasnull .
-
interpolate
Interpolates variables in a template string using"${name}" syntax.Replaces variables of the form
"${name}" with values from the map. This is similar to shell variable interpolation syntax.Example:
var vars = Map.of(
"name" ,"John" ,"city" ,"New York" ); interpolate("Hello ${name}, welcome to ${city}" , vars);// Returns: "Hello John, welcome to New York" - Parameters:
template- The template string with"${name}" variables.variables- The map containing the variable values.- Returns:
- The interpolated string with variables replaced, or the original template if variables is null or empty.
-
isAbsoluteUri
Efficiently determines whether a URL is of the pattern "xxx://xxx"- Parameters:
s- The string to test.- Returns:
true if it's an absolute path.
-
isAllNotBlank
Checks if all of the provided strings are not blank (not null, not empty, and not whitespace only).Returns
true only if all strings are not null, not empty, and contain non-whitespace characters. Returnsfalse if the array is null or empty, or if any string is null, empty, or whitespace only.Example:
isAllNotBlank();
// false isAllNotBlank(null );// false isAllNotBlank(null ,null );// false isAllNotBlank("" ,"" );// false isAllNotBlank(" " ," " );// false isAllNotBlank(null ,"hello" );// false isAllNotBlank("" ," " );// false isAllNotBlank("hello" ," " );// false isAllNotBlank("hello" );// true isAllNotBlank("hello" ,"world" );// true - Parameters:
values- The strings to check.- Returns:
true if all strings are not null, not empty, and not whitespace only,false otherwise.
-
isAllNotEmpty
Checks if all of the provided strings are not empty (not null and not zero-length).Returns
true only if all strings are not null and have a length greater than zero. Returnsfalse if the array is null or empty, or if any string is null or empty.Example:
isAllNotEmpty();
// false isAllNotEmpty(null );// false isAllNotEmpty(null ,null );// false isAllNotEmpty("" ,"" );// false isAllNotEmpty(null ,"hello" );// false isAllNotEmpty("" ," " );// false isAllNotEmpty("hello" );// true isAllNotEmpty("hello" ,"world" );// true isAllNotEmpty("hello" ," " );// true - Parameters:
values- The strings to check.- Returns:
true if all strings are not null and not empty,false otherwise.
-
isAlpha
Checks if a string contains only alphabetic characters (a-z, A-Z).Example:
isAlpha(
null );// false isAlpha("" );// false isAlpha("abc" );// true isAlpha("abc123" );// false isAlpha("abc def" );// false - Parameters:
str- The string to check.- Returns:
true if the string is not null, not empty, and contains only alphabetic characters.
-
isAlphaNumeric
Checks if a string contains only alphanumeric characters (a-z, A-Z, 0-9).Example:
isAlphaNumeric(
null );// false isAlphaNumeric("" );// false isAlphaNumeric("abc" );// true isAlphaNumeric("abc123" );// true isAlphaNumeric("abc def" );// false isAlphaNumeric("abc-123" );// false - Parameters:
str- The string to check.- Returns:
true if the string is not null, not empty, and contains only alphanumeric characters.
-
isAnyNotBlank
Checks if any of the provided strings are not blank (not null, not empty, and not whitespace only).Returns
true if at least one string is not null, not empty, and contains non-whitespace characters.Example:
isAnyNotBlank(
null ,null );// false isAnyNotBlank("" ,"" );// false isAnyNotBlank(" " ," " );// false isAnyNotBlank(null ,"hello" );// true isAnyNotBlank("" ," " ,"x" );// true isAnyNotBlank("hello" ,"world" );// true - Parameters:
values- The strings to check.- Returns:
true if at least one string is not null, not empty, and contains non-whitespace characters.
-
isAnyNotEmpty
Checks if any of the provided strings are not empty (not null and not zero-length).Returns
true if at least one string is not null and has a length greater than zero.Example:
isAnyNotEmpty(
null ,null );// false isAnyNotEmpty("" ,"" );// false isAnyNotEmpty(null ,"hello" );// true isAnyNotEmpty("" ," " );// true isAnyNotEmpty("hello" ,"world" );// true - Parameters:
values- The strings to check.- Returns:
true if at least one string is not null and not empty.
-
isBlank
Checks if a string is blank (null, empty, or whitespace only).Example:
isBlank(
null );// true isBlank("" );// true isBlank(" " );// true isBlank("hello" );// false - Parameters:
str- The string to check.- Returns:
true if the string is null, empty, or contains only whitespace characters.
-
isCreditCard
Checks if a string is a valid credit card number using the Luhn algorithm.Validates credit card numbers by:
- Removing spaces and hyphens
- Checking that all remaining characters are digits
- Verifying the number passes the Luhn algorithm check
- Ensuring the number is between 13-19 digits (standard credit card length)
Example:
isCreditCard(
null );// false isCreditCard("" );// false isCreditCard("4532015112830366" );// true (Visa test card) isCreditCard("4532-0151-1283-0366" );// true (with separators) isCreditCard("1234567890" );// false (invalid Luhn) - Parameters:
str- The string to check.- Returns:
true if the string is a valid credit card number.
-
isDecimal
Returnstrue if the specified string is numeric.- Parameters:
s- The string to check.- Returns:
true if the specified string is numeric.
-
isDigit
Checks if a string contains only digit characters (0-9).Example:
isDigit(
null );// false isDigit("" );// false isDigit("123" );// true isDigit("abc123" );// false isDigit("12.3" );// false - Parameters:
str- The string to check.- Returns:
true if the string is not null, not empty, and contains only digit characters.
-
isEmail
Checks if a string is a valid email address.Performs basic email validation using a simple regex pattern. This is not a complete RFC 5321/5322 validation, but covers most common email formats.
Example:
isEmail(
null );// false isEmail("" );// false isEmail("user@example.com" );// true isEmail("invalid.email" );// false - Parameters:
str- The string to check.- Returns:
true if the string is a valid email address.
-
isEmpty
Checks if a string is null or empty.Example:
isEmpty(
null );// true isEmpty("" );// true isEmpty("abc" );// false - Parameters:
str- The string to check.- Returns:
true if the string is null or empty.
-
isFirstNumberChar
Returnstrue if the specified character is a valid first character for a number.- Parameters:
c- The character to test.- Returns:
true if the specified character is a valid first character for a number.
-
isFloat
Returnstrue if the specified string is a floating point number.- Parameters:
s- The string to check.- Returns:
true if the specified string is a floating point number.
-
isInterned
Checks if a string is already interned.Returns
false if the input string isnull . A string is considered interned if it is the same object reference as its interned version.Examples:
String
s1 ="test" ;// String literal is automatically interned assertTrue(isInterned(s1 )); Strings2 =new String("test" );// New object, not interned assertFalse(isInterned(s2 )); Strings3 = intern(s2 );// Now interned assertTrue(isInterned(s3 ));- Parameters:
str- The string to check. Can benull .- Returns:
true if the string is interned,false otherwise.
-
isProbablyJson
Returnstrue if the specified string appears to be valid JSON.This method performs a simple heuristic check and does not strictly validate JSON syntax. Leading and trailing spaces are ignored.
Leading and trailing comments are not allowed.- Parameters:
s- The string to test.- Returns:
true if the specified string appears to be valid JSON.
-
isProbablyJsonArray
Returnstrue if the specified string appears to be a JSON array.This method performs a simple heuristic check and does not strictly validate JSON syntax.
- Parameters:
o- The object to test.ignoreWhitespaceAndComments- Iftrue , leading and trailing whitespace and comments will be ignored.- Returns:
true if the specified string appears to be a JSON array.
-
isProbablyJsonObject
Returnstrue if the specified string appears to be a JSON object.This method performs a simple heuristic check and does not strictly validate JSON syntax.
- Parameters:
o- The object to test.ignoreWhitespaceAndComments- Iftrue , leading and trailing whitespace and comments will be ignored.- Returns:
true if the specified string appears to be a JSON object.
-
isNotBlank
Checks if a string is not blank (not null, not empty, and not whitespace only).Example:
isNotBlank(
null );// false isNotBlank("" );// false isNotBlank(" " );// false isNotBlank("hello" );// true - Parameters:
str- The string to check.- Returns:
true if the string is not null, not empty, and contains non-whitespace characters.
-
isNumberChar
Returnstrue if the specified character is a valid number character.- Parameters:
c- The character to check.- Returns:
true if the specified character is a valid number character.
-
isNumeric
Returnstrue if this string can be parsed byparseNumber(String, Class).- Parameters:
s- The string to check.- Returns:
true if this string can be parsed without causing an exception.
-
isOneOf
Returnstrue if the specified string is one of the specified values.- Parameters:
s- The string to test. Can benull .values- The values to test. Can containnull .- Returns:
true if the specified string is one of the specified values.
-
isPhoneNumber
Checks if a string is a valid phone number.Performs basic phone number validation. Accepts various formats including:
- Digits only:
"1234567890" - With separators:
"(123) 456-7890" ,"123-456-7890" ,"123.456.7890" - With country code:
"+1 123-456-7890"
Example:
isPhoneNumber(
null );// false isPhoneNumber("" );// false isPhoneNumber("1234567890" );// true isPhoneNumber("(123) 456-7890" );// true isPhoneNumber("123" );// false - Parameters:
str- The string to check.- Returns:
true if the string is a valid phone number.
- Digits only:
-
isSimilar
Checks if two strings are similar based on a similarity threshold.Uses the
similarity(String, String)method to calculate similarity and compares it to the threshold.Example:
isSimilar(
"hello" ,"hello" ,0.8 );// true isSimilar("kitten" ,"sitting" ,0.8 );// false isSimilar("kitten" ,"sitting" ,0.5 );// true - Parameters:
str1- The first string.str2- The second string.threshold- The similarity threshold (0.0 to 1.0).- Returns:
true if the similarity is greater than or equal to the threshold,false otherwise.
-
isUri
Efficiently determines whether a URL is of the pattern "xxx:/xxx".The pattern matched is:
[a-z]{2,}\:\/.* Note that this excludes filesystem paths such as
"C:/temp" .- Parameters:
s- The string to test.- Returns:
true if it's an absolute path.
-
isValidDateFormat
Validates if a date string matches the specified date format.Uses
SimpleDateFormatto parse the date string according to the format pattern.Example:
isValidDateFormat(
"2023-12-25" ,"yyyy-MM-dd" );// true isValidDateFormat("25/12/2023" ,"dd/MM/yyyy" );// true isValidDateFormat("2023-13-25" ,"yyyy-MM-dd" );// false (invalid month) - Parameters:
dateStr- The date string to validate. Can benull .format- The date format pattern (e.g., "yyyy-MM-dd"). Can benull .- Returns:
true if the date string matches the format,false otherwise.
-
isValidHostname
Validates if a string is a valid hostname.Validates hostnames according to RFC 1123. A valid hostname:
- Can contain letters, digits, and hyphens
- Cannot start or end with a hyphen
- Each label (dot-separated part) can be up to 63 characters
- Total length can be up to 253 characters
- Labels cannot be empty
Example:
isValidHostname(
"example.com" );// true isValidHostname("sub.example.com" );// true isValidHostname("-invalid.com" );// false (starts with hyphen) isValidHostname("example..com" );// false (empty label) - Parameters:
hostname- The hostname string to validate. Can benull .- Returns:
true if the string is a valid hostname,false otherwise.
-
isValidIpAddress
Validates if a string is a valid IP address (IPv4 or IPv6).Supports both IPv4 (e.g., "192.168.1.1") and IPv6 (e.g., "2001:0db8:85a3:0000:0000:8a2e:0370:7334") formats.
Example:
isValidIpAddress(
"192.168.1.1" );// true isValidIpAddress("2001:0db8:85a3::8a2e:0370:7334" );// true isValidIpAddress("256.1.1.1" );// false isValidIpAddress("not.an.ip" );// false - Parameters:
ip- The IP address string to validate. Can benull .- Returns:
true if the string is a valid IP address,false otherwise.
-
isValidMacAddress
Validates if a string is a valid MAC address.Supports common MAC address formats:
- Colon-separated:
"00:1B:44:11:3A:B7" - Hyphen-separated:
"00-1B-44-11-3A-B7" - No separators:
"001B44113AB7"
Example:
isValidMacAddress(
"00:1B:44:11:3A:B7" );// true isValidMacAddress("00-1B-44-11-3A-B7" );// true isValidMacAddress("001B44113AB7" );// true isValidMacAddress("00:1B:44:11:3A" );// false (too short) - Parameters:
mac- The MAC address string to validate. Can benull .- Returns:
true if the string is a valid MAC address,false otherwise.
- Colon-separated:
-
isValidRegex
Validates if a string is a valid regular expression pattern.Attempts to compile the regex pattern to verify it's syntactically correct.
Example:
isValidRegex(
"[a-z]+" );// true isValidRegex("[a-z" );// false (unclosed bracket) isValidRegex("(test" );// false (unclosed parenthesis) - Parameters:
regex- The regex pattern to validate. Can benull .- Returns:
true if the string is a valid regex pattern,false otherwise.
-
isValidTimeFormat
Validates if a time string matches the specified time format.Uses
SimpleDateFormatto parse the time string according to the format pattern.Example:
isValidTimeFormat(
"14:30:00" ,"HH:mm:ss" );// true isValidTimeFormat("2:30 PM" ,"h:mm a" );// true isValidTimeFormat("25:00:00" ,"HH:mm:ss" );// false (invalid hour) - Parameters:
timeStr- The time string to validate. Can benull .format- The time format pattern (e.g., "HH:mm:ss"). Can benull .- Returns:
true if the time string matches the format,false otherwise.
-
isWhitespace
Checks if a character is whitespace.- Parameters:
c- The character to check.- Returns:
true if the character is whitespace.
-
isWhitespace
Checks if a string contains only whitespace characters.Example:
isWhitespace(
null );// false isWhitespace("" );// true isWhitespace(" " );// true isWhitespace("\t\n" );// true isWhitespace(" a " );// false - Parameters:
str- The string to check.- Returns:
true if the string is not null and contains only whitespace characters (or is empty).
-
join
Combines collection values into a simple comma-delimited string.- Parameters:
values- The values to join.- Returns:
- A comma-delimited string.
-
join
Join the specified tokens into a delimited string.- Parameters:
tokens- The tokens to join.d- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
join
Join the specified tokens into a delimited string.- Parameters:
tokens- The tokens to join.d- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
join
Joins the specified tokens into a delimited string and writes the output to the specified string builder.- Parameters:
tokens- The tokens to join.d- The delimiter.sb- The string builder to append the response to.- Returns:
- The same string builder passed in as
sb .
-
join
Join the specified tokens into a delimited string.- Parameters:
tokens- The tokens to join.d- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
join
Joins an array of integers with a delimiter.Example:
join(
new int []{1, 2, 3},"," );// "1,2,3" join(new int []{},"," );// "" - Parameters:
array- The array to join.delimiter- The delimiter string.- Returns:
- The joined string.
-
join
Joins the specified tokens into a delimited string.- Parameters:
tokens- The tokens to join.d- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
join
Join the specified tokens into a delimited string and writes the output to the specified string builder.- Parameters:
tokens- The tokens to join.d- The delimiter.sb- The string builder to append the response to.- Returns:
- The same string builder passed in as
sb .
-
join
Join the specified tokens into a delimited string.- Parameters:
tokens- The tokens to join.separator- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
join
Combines values into a simple comma-delimited string.- Parameters:
values- The values to join.- Returns:
- A comma-delimited string.
-
joine
Same asjoin(Collection, char)but escapes the delimiter if found in the tokens.- Parameters:
tokens- The tokens to join.d- The delimiter.- Returns:
- The delimited string. If
tokens isnull , returnsnull .
-
joinnl
Joins tokens with newlines.- Parameters:
tokens- The tokens to concatenate.- Returns:
- A string with the specified tokens contatenated with newlines.
-
kebabCase
Converts a string to kebab-case format.Handles various input formats:
- Space-separated: "hello world" → "hello-world"
- CamelCase: "helloWorld" → "hello-world"
- PascalCase: "HelloWorld" → "hello-world"
- Snake_case: "hello_world" → "hello-world"
Example:
kebabCase(
null );// null kebabCase("" );// "" kebabCase("hello world" );// "hello-world" kebabCase("helloWorld" );// "hello-world" kebabCase("HelloWorld" );// "hello-world" kebabCase("hello_world" );// "hello-world" - Parameters:
str- The string to convert.- Returns:
- The kebab-case string, or
null if input isnull .
-
lastIndexOf
Finds the index of the last occurrence of a substring within a string.Example:
lastIndexOf(
"hello world world" ,"world" );// 12 lastIndexOf("hello world" ,"xyz" );// -1 lastIndexOf(null ,"test" );// -1 - Parameters:
str- The string to search in.search- The substring to search for.- Returns:
- The index of the last occurrence, or
-1 if not found or if either parameter isnull .
-
lastIndexOfIgnoreCase
Finds the index of the last occurrence of a substring within a string, ignoring case.Example:
lastIndexOfIgnoreCase(
"Hello World World" ,"world" );// 12 lastIndexOfIgnoreCase("Hello World" ,"WORLD" );// 6 lastIndexOfIgnoreCase("hello world" ,"xyz" );// -1 - Parameters:
str- The string to search in.search- The substring to search for.- Returns:
- The index of the last occurrence, or
-1 if not found or if either parameter isnull .
-
lastNonWhitespaceChar
Returns the last non-whitespace character in the string.- Parameters:
s- The string to check.- Returns:
- The last non-whitespace character, or
0 if the string isnull , empty, or composed of only whitespace.
-
left
Returns the leftmost characters of a string.Example:
left(
null , 3);// null left("" , 3);// "" left("hello" , 3);// "hel" left("hello" , 10);// "hello" - Parameters:
str- The string to get characters from.len- The number of characters to get.- Returns:
- The leftmost characters, or
null if input isnull .
-
levenshteinDistance
Calculates the Levenshtein distance (edit distance) between two strings.The Levenshtein distance is the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into another.
Example:
levenshteinDistance(
"kitten" ,"sitting" );// 3 levenshteinDistance("hello" ,"hello" );// 0 levenshteinDistance("abc" ,"" );// 3 - Parameters:
str1- The first string.str2- The second string.- Returns:
- The Levenshtein distance between the two strings.
-
lineCount
Counts the number of lines in a string.Counts newline characters. A string ending without a newline is counted as one line.
Example:
lineCount(
"line1\nline2\nline3" );// 3 lineCount("single line" );// 1 lineCount("line1\r\nline2" );// 2 - Parameters:
str- The string to count lines in. Can benull .- Returns:
- The number of lines, or
0 if the string isnull or empty.
-
lowerCase
Null-safe convenience method forString.toLowerCase().Converts the string to lowercase if not null.
- Parameters:
s- The string to convert.- Returns:
- The lowercase string, or
null if the input wasnull . - See Also:
-
mapped
Maps each element of a string array using the specified function.Returns
null if the array isnull . Returns an array withnull elements if the function isnull or returnsnull .Examples:
String[]
array = {"foo" ,"bar" ,"baz" }; String[]uppercased = map(array , String::toUpperCase);// Returns: ["FOO", "BAR", "BAZ"] String[]prefixed = map(array , s ->"prefix-" + s);// Returns: ["prefix-foo", "prefix-bar", "prefix-baz"] - Parameters:
array- The array to map. Can benull .mapper- The function to apply to each element. Can benull .- Returns:
- A new array with the mapped elements, or
null if the array wasnull .
-
matches
Checks if a string matches a regular expression pattern.Example:
matches(
"12345" ,"\\d+" );// true matches("abc123" ,"^[a-z]+\\d+$" );// true matches("abc" ,"\\d+" );// false - Parameters:
str- The string to check.regex- The regular expression pattern.- Returns:
true if the string matches the pattern,false otherwise.- Throws:
PatternSyntaxException- If the regex pattern is invalid.
-
metaphone
Generates a Metaphone code for a string.Metaphone is a phonetic algorithm that produces codes representing how words sound. It's more accurate than Soundex for English words.
Example:
metaphone(
"Smith" );// "SM0" metaphone("Smythe" );// "SM0" metaphone("Robert" );// "RBRT" - Parameters:
str- The string to generate a Metaphone code for. Can benull .- Returns:
- The Metaphone code, or
null if input isnull or empty.
-
mid
Returns the middle characters of a string.Example:
mid(
null , 1, 3);// null mid("" , 1, 3);// "" mid("hello" , 1, 3);// "ell" mid("hello" , 1, 10);// "ello" - Parameters:
str- The string to get characters from.pos- The starting position (0-based).len- The number of characters to get.- Returns:
- The middle characters, or
null if input isnull .
-
mostFrequentChar
Finds the most frequent character in a string.Returns the character that appears most often. If multiple characters have the same frequency, returns the first one encountered.
Example:
mostFrequentChar(
"hello" );// 'l' mostFrequentChar("aabbcc" );// 'a' (first encountered) - Parameters:
str- The string to analyze. Can benull .- Returns:
- The most frequent character, or
'\0' if the string isnull or empty.
-
naturalCompare
Performs natural string comparison that handles numbers correctly.Compares strings in a way that numbers are compared numerically rather than lexicographically. For example, "file2.txt" comes before "file10.txt" in natural order.
Example:
naturalCompare(
"file2.txt" ,"file10.txt" );// negative (2 < 10) naturalCompare("file10.txt" ,"file2.txt" );// positive (10 > 2) naturalCompare("file1.txt" ,"file1.txt" );// 0 (equal) - Parameters:
str1- The first string.str2- The second string.- Returns:
- A negative integer, zero, or a positive integer as the first string is less than, equal to, or greater than the second.
-
normalizeUnicode
Normalizes Unicode characters in a string.Uses Unicode normalization form NFD (Canonical Decomposition).
Example:
normalizeUnicode(
"café" );// Normalized form - Parameters:
str- The string to normalize. Can benull .- Returns:
- The normalized string, or
null if input isnull .
-
normalizeWhitespace
Normalizes all whitespace in a string to single spaces.Example:
normalizeWhitespace(
"hello \t\n world" );// "hello world" normalizeWhitespace(" hello world " );// "hello world" - Parameters:
str- The string to normalize.- Returns:
- The normalized string, or
null if input isnull .
-
notContains
Checks if a string does not contain the specified character.This is the inverse of
contains(String, char). Returnstrue if the string isnull or does not contain the character.Example:
notContains(
"Hello World" ,'x' );// true notContains("Hello World" ,'o' );// false notContains(null ,'a' );// true - Parameters:
s- The string to check.c- The character to check for.- Returns:
true if the string does not contain the specified character.- See Also:
-
notContains
Checks if a string does not contain the specified substring.This is the inverse of
contains(String, CharSequence). Returnstrue if the string isnull or does not contain the substring.Example:
notContains(
"Hello World" ,"Foo" );// true notContains("Hello World" ,"World" );// false notContains(null ,"Hello" );// true - Parameters:
s- The string to check.substring- The substring to check for.- Returns:
true if the string does not contain the specified substring.- See Also:
-
notContains
Checks if a string does not contain the specified substring.This is the inverse of
contains(String, String). Returnstrue if the string isnull or does not contain the substring.Example:
notContains(
"Hello World" ,"Foo" );// true notContains("Hello World" ,"World" );// false notContains(null ,"Hello" );// true - Parameters:
s- The string to check.substring- The substring to check for.- Returns:
true if the string does not contain the specified substring.- See Also:
-
notContainsAll
Checks if a string does not contain all of the specified characters.This is the inverse of
containsAll(String, char...). Returnstrue if:- The string is
null - The values array is
null or empty - Any of the specified characters are not found in the string
Example:
notContainsAll(
"Hello World" ,'H' ,'x' );// true (missing 'x') notContainsAll("Hello World" ,'H' ,'e' ,'l' );// false (contains all) notContainsAll(null ,'a' );// true - Parameters:
s- The string to check.values- The characters to check for.- Returns:
true if the string does not contain all of the specified characters.- See Also:
- The string is
-
notContainsAll
Checks if a string does not contain all of the specified substrings.This is the inverse of
containsAll(String, CharSequence...). Returnstrue if:- The string is
null - The values array is
null or empty - Any of the specified substrings are not found in the string
Example:
notContainsAll(
"Hello World" ,"Hello" ,"Foo" );// true (missing "Foo") notContainsAll("Hello World" ,"Hello" ,"World" );// false (contains all) notContainsAll(null ,"Hello" );// true - Parameters:
s- The string to check.values- The substrings to check for.- Returns:
true if the string does not contain all of the specified substrings.- See Also:
- The string is
-
notContainsAll
Checks if a string does not contain all of the specified substrings.This is the inverse of
containsAll(String, String...). Returnstrue if:- The string is
null - The values array is
null or empty - Any of the specified substrings are not found in the string
Example:
notContainsAll(
"Hello World" ,"Hello" ,"Foo" );// true (missing "Foo") notContainsAll("Hello World" ,"Hello" ,"World" );// false (contains all) notContainsAll(null ,"Hello" );// true - Parameters:
s- The string to check.values- The substrings to check for.- Returns:
true if the string does not contain all of the specified substrings.- See Also:
- The string is
-
notContainsAny
Checks if a string does not contain any of the specified characters.This is the inverse of
containsAny(String, char...). Returnstrue if:- The string is
null - The values array is
null or empty - None of the specified characters are found in the string
Example:
notContainsAny(
"Hello World" ,'x' ,'y' );// true notContainsAny("Hello World" ,'o' ,'x' );// false (contains 'o') notContainsAny(null ,'a' );// true - Parameters:
s- The string to check.values- The characters to check for.- Returns:
true if the string does not contain any of the specified characters.- See Also:
- The string is
-
notContainsAny
Checks if a string does not contain any of the specified substrings.This is the inverse of
containsAny(String, CharSequence...). Returnstrue if:- The string is
null - The values array is
null or empty - None of the specified substrings are found in the string
Example:
notContainsAny(
"Hello World" ,"Foo" ,"Bar" );// true notContainsAny("Hello World" ,"Hello" ,"Foo" );// false (contains "Hello") notContainsAny(null ,"Hello" );// true - Parameters:
s- The string to check.values- The substrings to check for.- Returns:
true if the string does not contain any of the specified substrings.- See Also:
- The string is
-
notContainsAny
Checks if a string does not contain any of the specified substrings.This is the inverse of
containsAny(String, String...). Returnstrue if:- The string is
null - The values array is
null or empty - None of the specified substrings are found in the string
Example:
notContainsAny(
"Hello World" ,"Foo" ,"Bar" );// true notContainsAny("Hello World" ,"Hello" ,"Foo" );// false (contains "Hello") notContainsAny(null ,"Hello" );// true - Parameters:
s- The string to check.values- The substrings to check for.- Returns:
true if the string does not contain any of the specified substrings.- See Also:
- The string is
-
obfuscate
Returns an obfuscated version of the specified string.- Parameters:
s- The string to obfuscate.- Returns:
- The obfuscated string with most characters replaced by asterisks.
-
ordinal
Converts a number to its ordinal form (1st, 2nd, 3rd, 4th, etc.).Example:
ordinal(
1 );// "1st" ordinal(2 );// "2nd" ordinal(3 );// "3rd" ordinal(4 );// "4th" ordinal(11 );// "11th" ordinal(21 );// "21st" - Parameters:
number- The number to convert.- Returns:
- The ordinal string representation of the number.
-
padCenter
Center pads a string with a specified character.Example:
padCenter(
null , 5,' ' );// " " padCenter("" , 5,' ' );// " " padCenter("hi" , 6,' ' );// " hi " padCenter("hi" , 7,' ' );// " hi " padCenter("hello" , 3,' ' );// "hello" - Parameters:
str- The string to pad.size- The desired total string length.padChar- The character to pad with.- Returns:
- The center-padded string.
-
padLeft
Left pads a string with a specified character.Example:
padLeft(
null , 5,' ' );// " " padLeft("" , 5,' ' );// " " padLeft("hello" , 8,' ' );// " hello" padLeft("hello" , 3,' ' );// "hello" padLeft("123" , 5,'0' );// "00123" - Parameters:
str- The string to pad.size- The desired total string length.padChar- The character to pad with.- Returns:
- The left-padded string.
-
padRight
Right pads a string with a specified character.Example:
padRight(
null , 5,' ' );// " " padRight("" , 5,' ' );// " " padRight("hello" , 8,' ' );// "hello " padRight("hello" , 3,' ' );// "hello" padRight("123" , 5,'0' );// "12300" - Parameters:
str- The string to pad.size- The desired total string length.padChar- The character to pad with.- Returns:
- The right-padded string.
-
parseCharacter
Converts aString to aCharacter - Parameters:
o- The string to convert.- Returns:
- The first character of the string if the string is of length 1, or
null if the string isnull or empty. - Throws:
IllegalArgumentException- If the string length is not 1.
-
parseFloat
Same asFloat.parseFloat(String)but removes any underscore characters first.Allows for better readability of numeric literals (e.g.,
"1_000.5" ).- Parameters:
value- The string to parse.- Returns:
- The parsed float value.
- Throws:
NumberFormatException- If the string cannot be parsed.NullPointerException- If the string isnull .
-
parseInt
Same asInteger.parseInt(String)but removes any underscore characters first.Allows for better readability of numeric literals (e.g.,
"1_000_000" ).- Parameters:
value- The string to parse.- Returns:
- The parsed integer value.
- Throws:
NumberFormatException- If the string cannot be parsed.NullPointerException- If the string isnull .
-
parseIntWithSuffix
Converts a string containing a possible multiplier suffix to an integer.The string can contain any of the following multiplier suffixes:
"K" - x 1024"M" - x 1024*1024"G" - x 1024*1024*1024"k" - x 1000"m" - x 1000*1000"g" - x 1000*1000*1000
- Parameters:
s- The string to parse.- Returns:
- The parsed value.
-
parseLong
Same asLong.parseLong(String)but removes any underscore characters first.Allows for better readability of numeric literals (e.g.,
"1_000_000" ).- Parameters:
value- The string to parse.- Returns:
- The parsed long value.
- Throws:
NumberFormatException- If the string cannot be parsed.NullPointerException- If the string isnull .
-
parseLongWithSuffix
Converts a string containing a possible multiplier suffix to a long.The string can contain any of the following multiplier suffixes:
"K" - x 1024"M" - x 1024*1024"G" - x 1024*1024*1024"T" - x 1024*1024*1024*1024"P" - x 1024*1024*1024*1024*1024"k" - x 1000"m" - x 1000*1000"g" - x 1000*1000*1000"t" - x 1000*1000*1000*1000"p" - x 1000*1000*1000*1000*1000
- Parameters:
s- The string to parse.- Returns:
- The parsed value.
-
parseMap
public static Map<String,String> parseMap(String str, char keyValueDelimiter, char entryDelimiter, boolean trimKeys) Parses a string containing key-value pairs into a map.Splits the string by the entry delimiter, then splits each entry by the key-value delimiter.
Example:
parseMap(
"key1=value1,key2=value2" ,'=' ,',' ,false );// {"key1":"value1","key2":"value2"} parseMap(" key1 = value1 ; key2 = value2 " ,'=' ,';' ,true );// {"key1":"value1","key2":"value2"} - Parameters:
str- The string to parse. Can benull .keyValueDelimiter- The character that separates keys from values.entryDelimiter- The character that separates entries.trimKeys- Iftrue , trims whitespace from keys and values.- Returns:
- A map containing the parsed key-value pairs, or an empty map if the string is
null or empty.
-
parseNumber
Parses a number from the specified string.Supports Java 7+ numeric literals with underscores (e.g.,
"1_000_000" ). The underscores are automatically removed before parsing.- Parameters:
s- The string to parse the number from.type- The number type to created. Can be any of the following:- Integer (or
int primitive) - Long (or
long primitive) - Short (or
short primitive) - Byte (or
byte primitive) - Float (or
float primitive) - Double (or
double primitive) - BigInteger
- BigDecimal
- AtomicInteger
- AtomicLong
null orNumber , uses the best guess.- Integer (or
- Returns:
- The parsed number, or
null if the string was null.
-
pascalCase
Converts a string to PascalCase format.Handles various input formats:
- Space-separated: "hello world" → "HelloWorld"
- CamelCase: "helloWorld" → "HelloWorld"
- Snake_case: "hello_world" → "HelloWorld"
- Kebab-case: "hello-world" → "HelloWorld"
Example:
pascalCase(
null );// null pascalCase("" );// "" pascalCase("hello world" );// "HelloWorld" pascalCase("helloWorld" );// "HelloWorld" pascalCase("hello_world" );// "HelloWorld" pascalCase("hello-world" );// "HelloWorld" - Parameters:
str- The string to convert.- Returns:
- The PascalCase string, or
null if input isnull .
-
pluralize
Pluralizes a word based on a count.Simple pluralization that adds "s" to most words, with basic rules for words ending in "s", "x", "z", "ch", "sh" (add "es"), and words ending in "y" preceded by a consonant (replace "y" with "ies").
Example:
pluralize(
"cat" ,1 );// "cat" pluralize("cat" ,2 );// "cats" pluralize("box" ,2 );// "boxes" pluralize("city" ,2 );// "cities" - Parameters:
word- The word to pluralize.count- The count to determine if pluralization is needed.- Returns:
- The pluralized word if count is not 1, otherwise the original word.
-
random
Generated a random UUID with the specified number of characters.Characters are composed of lower-case ASCII letters and numbers only.
This method conforms to the restrictions for hostnames as specified in RFC 952 Since each character has 36 possible values, the square approximation formula for the number of generated IDs that would produce a 50% chance of collision is:
sqrt(36^N) . Dividing this number by 10 gives you an approximation of the number of generated IDs needed to produce a <1% chance of collision.For example, given 5 characters, the number of generated IDs need to produce a <1% chance of collision would be:
sqrt(36^5)/10=777 - Parameters:
numchars- The number of characters in the generated UUID.- Returns:
- A new random UUID.
-
randomAlphabetic
Generates a random alphabetic string of the specified length.Characters are composed of upper-case and lower-case ASCII letters (a-z, A-Z).
Example:
randomAlphabetic(
5 );// "aBcDe" - Parameters:
length- The length of the generated string.- Returns:
- A new random alphabetic string.
-
randomAlphanumeric
Generates a random alphanumeric string of the specified length.Characters are composed of upper-case and lower-case ASCII letters and digits (a-z, A-Z, 0-9).
Example:
randomAlphanumeric(
8 );// "aB3dE5fG" - Parameters:
length- The length of the generated string.- Returns:
- A new random alphanumeric string.
-
randomAscii
Generates a random ASCII string of the specified length.Characters are composed of printable ASCII characters (32-126).
Example:
randomAscii(
10 );// "!@#$%^&*()" - Parameters:
length- The length of the generated string.- Returns:
- A new random ASCII string.
-
randomNumeric
Generates a random numeric string of the specified length.Characters are composed of digits (0-9).
Example:
randomNumeric(
6 );// "123456" - Parameters:
length- The length of the generated string.- Returns:
- A new random numeric string.
-
randomString
Generates a random string of the specified length using characters from the given character set.Each character in the generated string is randomly selected from the provided character set.
Example:
randomString(
5 ,"ABC" );// "BACAB" - Parameters:
length- The length of the generated string.chars- The character set to use. Must not be null or empty.- Returns:
- A new random string.
- Throws:
IllegalArgumentException- If chars is null or empty, or length is negative.
-
readabilityScore
Calculates a simple readability score for a string.Uses a simplified Flesch Reading Ease-like formula based on:
- Average words per sentence
- Average syllables per word (estimated)
Example:
readabilityScore(
"The cat sat." );// Higher score (simple) readabilityScore("The sophisticated..." );// Lower score (complex) - Parameters:
str- The string to analyze. Can benull .- Returns:
- A readability score from 0-100, or
0.0 if the string isnull or empty.
-
readable
Converts an arbitrary object to a readable string format suitable for debugging and testing.This method provides intelligent formatting for various Java types, recursively processing nested structures to create human-readable representations. It's extensively used throughout the Juneau framework for test assertions and debugging output.
Type-Specific Formatting:
- null: Returns
null - Optional: Recursively formats the contained value (or
null if empty) - Collections: Formats as
"[item1,item2,item3]" with comma-separated elements - Maps: Formats as
"{key1=value1,key2=value2}" with comma-separated entries - Map.Entry: Formats as
"key=value" - Arrays: Converts to list format
"[item1,item2,item3]" - Iterables/Iterators/Enumerations: Converts to list and formats recursively
- GregorianCalendar: Formats as ISO instant timestamp
- Date: Formats as ISO instant string (e.g.,
"2023-12-25T10:30:00Z" ) - InputStream: Converts to hexadecimal representation
- Reader: Reads content and returns as string
- File: Reads file content and returns as string
- byte[]: Converts to hexadecimal representation
- Enum: Returns the enum name via
Enum.name() - All other types: Uses
Object.toString()
Examples:
// Collections readable(List.of("a", "b", "c"))// Returns: "[a,b,c]" readable(Set.of(1, 2, 3))// Returns: "[1,2,3]" (order may vary) // Maps readable(Map.of("foo", "bar", "baz", 123))// Returns: "{foo=bar,baz=123}" // Arrays readable(ints(1, 2, 3))// Returns: "[1,2,3]" readable(new String[]{"a", "b"})// Returns: "[a,b]" // Nested structures readable(List.of(Map.of("x", 1), Set.of("a", "b")))// Returns: "[{x=1},[a,b]]" // Special types readable(Optional.of("test"))// Returns: "test" readable(Optional.empty())// Returns: null readable(new Date(1640995200000L))// Returns: "2022-01-01T00:00:00Z" readable(MyEnum.FOO)// Returns: "FOO" Recursive Processing:
The method recursively processes nested structures, so complex objects containing collections, maps, and arrays are fully flattened into readable format. This makes it ideal for test assertions where you need to compare complex object structures.
Error Handling:
IO operations (reading files, streams) are wrapped in safe() calls, converting any exceptions to RuntimeExceptions. Binary data (InputStreams, byte arrays) is converted to hexadecimal representation for readability.
- Parameters:
o- The object to convert to readable format. Can benull .- Returns:
- A readable string representation of the object, or
null if the input wasnull .
- null: Returns
-
remove
Removes all occurrences of a substring from a string.Example:
remove(
null ,"x" );// null remove("hello" ,null );// "hello" remove("hello world" ,"o" );// "hell wrld" remove("hello world" ,"xyz" );// "hello world" - Parameters:
str- The string to process.remove- The substring to remove.- Returns:
- The string with all occurrences of the substring removed, or
null if input isnull .
-
removeAccents
Removes diacritical marks (accents) from characters in a string.Normalizes the string to NFD form and removes combining diacritical marks.
Example:
removeAccents(
"café" );// "cafe" removeAccents("naïve" );// "naive" removeAccents("résumé" );// "resume" - Parameters:
str- The string to remove accents from. Can benull .- Returns:
- The string with accents removed, or
null if input isnull .
-
removeAll
Removes multiple substrings from a string.Example:
removeAll(
"hello world test" ,"hello" ,"test" );// " world " removeAll(null ,"x" );// null - Parameters:
str- The string to process.remove- The substrings to remove.- Returns:
- The string with all specified substrings removed, or
null if input isnull .
-
removeControlChars
Removes control characters from a string, replacing them with spaces.Example:
removeControlChars(
"hello world" );// "hello world" removeControlChars("hello\nworld" );// "hello\nworld" - Parameters:
str- The string to process.- Returns:
- The string with control characters replaced by spaces (except whitespace control chars), or
null if input isnull .
-
removeEnd
Removes a suffix from a string if present.Example:
removeEnd(
null ,"x" );// null removeEnd("hello" ,null );// "hello" removeEnd("hello world" ,"world" );// "hello " removeEnd("hello world" ,"xyz" );// "hello world" - Parameters:
str- The string to process.suffix- The suffix to remove.- Returns:
- The string with the suffix removed if present, or
null if input isnull .
-
removeNonPrintable
Removes non-printable characters from a string.Example:
removeNonPrintable(
"hello world" );// "helloworld" - Parameters:
str- The string to process.- Returns:
- The string with non-printable characters removed, or
null if input isnull .
-
removeStart
Removes a prefix from a string if present.Example:
removeStart(
null ,"x" );// null removeStart("hello" ,null );// "hello" removeStart("hello world" ,"hello" );// " world" removeStart("hello world" ,"xyz" );// "hello world" - Parameters:
str- The string to process.prefix- The prefix to remove.- Returns:
- The string with the prefix removed if present, or
null if input isnull .
-
removeUnderscores
Removes all underscore characters from a string.This method is commonly used to process numeric literals that may contain underscores for readability (e.g.,
"1_000_000" becomes"1000000" ), as Java allows underscores in numeric literals but some parsing methods do not support them.If the string does not contain any underscores, the original string is returned (no new object created).
Example:
removeUnderscores(
"1_000_000" );// "1000000" removeUnderscores("1_000.5" );// "1000.5" removeUnderscores("hello_world" );// "helloworld" removeUnderscores("no_underscores" );// "nounderscores" removeUnderscores("Hello" );// "Hello" (no change, same object returned) - Parameters:
value- The string from which to remove underscores. Must not benull .- Returns:
- A new string with all underscores removed, or the original string if it contains no underscores.
- Throws:
IllegalArgumentException- Ifvalue isnull .- See Also:
-
repeat
Creates a repeated pattern.- Parameters:
count- The number of times to repeat the pattern.pattern- The pattern to repeat.- Returns:
- A new string consisting of the repeated pattern.
-
replaceUnicodeSequences
Replaces"\\uXXXX" character sequences with their unicode characters.- Parameters:
s- The string to replace unicode sequences in.- Returns:
- A string with unicode sequences replaced.
-
reverse
Reverses a string.Example:
reverse(
null );// null reverse("" );// "" reverse("hello" );// "olleh" - Parameters:
str- The string to reverse.- Returns:
- The reversed string, or
null if input isnull .
-
right
Returns the rightmost characters of a string.Example:
right(
null , 3);// null right("" , 3);// "" right("hello" , 3);// "llo" right("hello" , 10);// "hello" - Parameters:
str- The string to get characters from.len- The number of characters to get.- Returns:
- The rightmost characters, or
null if input isnull .
-
sanitize
Basic HTML/XML sanitization - removes or escapes potentially dangerous content.Removes HTML/XML tags and escapes special characters to prevent XSS attacks. This is a basic sanitization - for production use, consider a more robust library.
Example:
sanitize(
"<script>alert('xss')</script>" );// "<script>alert('xss')</script>" sanitize("Hello <b>World</b>" );// "Hello <b>World</b>" - Parameters:
str- The string to sanitize.- Returns:
- The sanitized string with HTML/XML tags escaped, or
null if input isnull .
-
similarity
Calculates the similarity percentage between two strings using Levenshtein distance.Returns a value between 0.0 (completely different) and 1.0 (identical).
Example:
similarity(
"hello" ,"hello" );// 1.0 (100%) similarity("kitten" ,"sitting" );// ~0.57 (57%) similarity("abc" ,"xyz" );// 0.0 (0%) - Parameters:
str1- The first string.str2- The second string.- Returns:
- A similarity value between 0.0 and 1.0, where 1.0 means identical.
-
snakeCase
Converts a string to snake_case format.Handles various input formats:
- Space-separated: "hello world" → "hello_world"
- CamelCase: "helloWorld" → "hello_world"
- PascalCase: "HelloWorld" → "hello_world"
- Kebab-case: "hello-world" → "hello_world"
Example:
snakeCase(
null );// null snakeCase("" );// "" snakeCase("hello world" );// "hello_world" snakeCase("helloWorld" );// "hello_world" snakeCase("HelloWorld" );// "hello_world" snakeCase("hello-world" );// "hello_world" - Parameters:
str- The string to convert.- Returns:
- The snake_case string, or
null if input isnull .
-
sort
Sorts a string array in natural order.Returns
null if the array isnull . This method creates a copy of the array and sorts it, leaving the original array unchanged.Examples:
String[]
array = {"zebra" ,"apple" ,"banana" }; String[]sorted = sort(array );// Returns: ["apple", "banana", "zebra"] - Parameters:
array- The array to sort. Can benull .- Returns:
- A new sorted array, or
null if the array wasnull .
-
sortIgnoreCase
Sorts a string array in case-insensitive order.Returns
null if the array isnull . This method creates a copy of the array and sorts it using case-insensitive comparison, leaving the original array unchanged.Examples:
String[]
array = {"Zebra" ,"apple" ,"Banana" }; String[]sorted = sortIgnoreCase(array );// Returns: ["apple", "Banana", "Zebra"] - Parameters:
array- The array to sort. Can benull .- Returns:
- A new sorted array (case-insensitive), or
null if the array wasnull .
-
soundex
Generates a Soundex code for a string.Soundex is a phonetic algorithm for indexing names by sound. The code consists of a letter followed by three digits. Similar-sounding names produce the same code.
Example:
soundex(
"Smith" );// "S530" soundex("Smythe" );// "S530" soundex("Robert" );// "R163" - Parameters:
str- The string to generate a Soundex code for. Can benull .- Returns:
- The Soundex code (1 letter + 3 digits), or
null if input isnull or empty.
-
split
Splits a comma-delimited list into a list of strings.- Parameters:
s- The string to split.- Returns:
- A list of split strings, or an empty list if the input is
null .
-
split
Splits a character-delimited string into a string array.Does not split on escaped-delimiters (e.g. "\,"); Resulting tokens are trimmed of whitespace.
NOTE: This behavior is different than the Jakarta equivalent. split("a,b,c",',') -> {"a","b","c"} split("a, b ,c ",',') -> {"a","b","c"} split("a,,c",',') -> {"a","","c"} split(",,",',') -> {"","",""} split("",',') -> {} split(null,',') -> null split("a,b\,c,d", ',', false) -> {"a","b\,c","d"} split("a,b\\,c,d", ',', false) -> {"a","b\","c","d"} split("a,b\,c,d", ',', true) -> {"a","b,c","d"}
- Parameters:
s- The string to split. Can benull .c- The character to split on.- Returns:
- The tokens, or
null if the string was null.
-
split
Same assplita(java.lang.String)but consumes the tokens instead of creating an array.- Parameters:
s- The string to split.c- The character to split on.consumer- The consumer of the tokens.
-
split
Same assplita(java.lang.String)but limits the number of tokens returned.- Parameters:
s- The string to split. Can benull .c- The character to split on.limit- The maximum number of tokens to return.- Returns:
- The tokens, or
null if the string was null.
-
split
Same assplita(java.lang.String)but consumes the tokens instead of creating an array.- Parameters:
s- The string to split.consumer- The consumer of the tokens.
-
splita
Splits a comma-delimited list into an array of strings.- Parameters:
s- The string to split.- Returns:
- An array of split strings.
-
splita
Splits a character-delimited string into a string array.Does not split on escaped-delimiters (e.g. "\,"); Resulting tokens are trimmed of whitespace.
NOTE: This behavior is different than the Jakarta equivalent. split("a,b,c",',') -> {"a","b","c"} split("a, b ,c ",',') -> {"a","b","c"} split("a,,c",',') -> {"a","","c"} split(",,",',') -> {"","",""} split("",',') -> {} split(null,',') -> null split("a,b\,c,d", ',', false) -> {"a","b\,c","d"} split("a,b\\,c,d", ',', false) -> {"a","b\","c","d"} split("a,b\,c,d", ',', true) -> {"a","b,c","d"}
- Parameters:
s- The string to split. Can benull .c- The character to split on.- Returns:
- The tokens, or
null if the string was null.
-
splita
Same assplita(String, char)but limits the number of tokens returned.- Parameters:
s- The string to split. Can benull .c- The character to split on.limit- The maximum number of tokens to return.- Returns:
- The tokens, or
null if the string was null.
-
splita
Same assplita(String, char)except splits all strings in the input and returns a single result.- Parameters:
s- The string to split. Can benull .c- The character to split on.- Returns:
- The tokens, or null if the input array was null
-
splitMap
Splits a list of key-value pairs into an ordered map.Example:
String
in ="foo=1;bar=2" ; Mapmap = StringUtils.splitMap (in,';' ,'=' ,true );- Parameters:
s- The string to split.trim- Trim strings after parsing.- Returns:
- The parsed map, or null if the string was null.
-
splitMethodArgs
Splits the method arguments in the signature of a method.- Parameters:
s- The arguments to split.- Returns:
- The split arguments, or null if the input string is null.
-
splitNested
Splits a comma-delimited list containing "nesting constructs". Nesting constructs are simple embedded "{...}" comma-delimted lists. Example: "a{b,c},d" -> ["a{b,c}","d"] Handles escapes and trims whitespace from tokens.- Parameters:
s- The input string.- Returns:
- The results, or
null if the input wasnull .
An empty string results in an empty array.
-
splitNestedInner
Splits a nested comma-delimited list. Nesting constructs are simple embedded "{...}" comma-delimted lists. Example: "a{b,c{d,e}}" -> ["b","c{d,e}"] Handles escapes and trims whitespace from tokens.- Parameters:
s- The input string.- Returns:
- The results, or
null if the input wasnull .
An empty string results in an empty array.
-
splitQuoted
Splits a space-delimited string with optionally quoted arguments.Examples:
"foo" =>["foo"] " foo " =>["foo"] "foo bar baz" =>["foo","bar","baz"] "foo 'bar baz'" =>["foo","bar baz"] "foo \"bar baz\"" =>["foo","bar baz"] "foo 'bar\'baz'" =>["foo","bar'baz"]
- Parameters:
s- The input string.- Returns:
- The results, or
null if the input wasnull .
An empty string results in an empty array.
-
splitQuoted
Same assplitQuoted(String)but allows you to optionally keep the quote characters.- Parameters:
s- The input string.keepQuotes- Iftrue , quote characters are kept on the tokens.- Returns:
- The results, or
null if the input wasnull .
An empty string results in an empty array.
-
startsWith
An efficient method for checking if a string starts with a character.- Parameters:
s- The string to check. Can benull .c- The character to check for.- Returns:
true if the specified string is notnull and starts with the specified character.
-
startsWithIgnoreCase
Checks if a string starts with a prefix, ignoring case.Example:
startsWithIgnoreCase(
"Hello World" ,"hello" );// true startsWithIgnoreCase("Hello World" ,"HELLO" );// true startsWithIgnoreCase("hello world" ,"world" );// false - Parameters:
str- The string to check.prefix- The prefix to check for.- Returns:
true if the string starts with the prefix (ignoring case),false otherwise.
-
stringSupplier
Takes a supplier of any type and returns aSupplier<String>.Useful when passing arguments to loggers.
- Parameters:
s- The supplier.- Returns:
- A string supplier that calls
readable(Object)on the supplied value.
-
strip
Strips the first and last character from a string.- Parameters:
s- The string to strip.- Returns:
- The striped string, or the same string if the input was
null or less than length 2.
-
stripInvalidHttpHeaderChars
Strips invalid characters such as CTRL characters from a string meant to be encoded as an HTTP header value.- Parameters:
s- The string to strip chars from.- Returns:
- The string with invalid characters removed.
-
substringAfter
Returns the substring after the first occurrence of a separator.Example:
substringAfter(
null ,"." );// null substringAfter("hello.world" ,null );// "" substringAfter("hello.world" ,"." );// "world" substringAfter("hello.world" ,"xyz" );// "" - Parameters:
str- The string to get a substring from.separator- The separator string.- Returns:
- The substring after the first occurrence of the separator, or empty string if separator not found.
-
substringBefore
Returns the substring before the first occurrence of a separator.Example:
substringBefore(
null ,"." );// null substringBefore("hello.world" ,null );// "hello.world" substringBefore("hello.world" ,"." );// "hello" substringBefore("hello.world" ,"xyz" );// "hello.world" - Parameters:
str- The string to get a substring from.separator- The separator string.- Returns:
- The substring before the first occurrence of the separator, or the original string if separator not found.
-
substringBetween
Returns the substring between two delimiters.Example:
substringBetween(
null ,"<" ,">" );// null substringBetween("<hello>" ,"<" ,">" );// "hello" substringBetween("<hello>" ,"[" ,"]" );// null - Parameters:
str- The string to get a substring from.open- The opening delimiter.close- The closing delimiter.- Returns:
- The substring between the delimiters, or
null if delimiters not found.
-
swapCase
Swaps the case of all characters in a string.Example:
swapCase(
"Hello World" );// "hELLO wORLD" swapCase("ABC123xyz" );// "abc123XYZ" - Parameters:
str- The string to process.- Returns:
- The string with case swapped, or
null if input isnull .
-
titleCase
Converts a string to Title Case format (first letter of each word capitalized, separated by spaces).Handles various input formats:
- CamelCase: "helloWorld" → "Hello World"
- PascalCase: "HelloWorld" → "Hello World"
- Snake_case: "hello_world" → "Hello World"
- Kebab-case: "hello-world" → "Hello World"
Example:
titleCase(
null );// null titleCase("" );// "" titleCase("hello world" );// "Hello World" titleCase("helloWorld" );// "Hello World" titleCase("hello_world" );// "Hello World" titleCase("hello-world" );// "Hello World" - Parameters:
str- The string to convert.- Returns:
- The Title Case string, or
null if input isnull .
-
toCdl
Converts the specified object to a comma-delimited list.- Parameters:
o- The object to convert.- Returns:
- The specified object as a comma-delimited list.
-
toHex
Converts the specified byte into a 2 hexadecimal characters.- Parameters:
b- The number to convert to hex.- Returns:
- A
containing the specified characters.char [2]
-
toHex
Converts a byte array into a simple hexadecimal character string.- Parameters:
bytes- The bytes to convert to hexadecimal.- Returns:
- A new string consisting of hexadecimal characters.
-
toHex
Converts the contents of the specified input stream to a hex string.- Parameters:
is- The input stream to convert.- Returns:
- The hex string representation of the input stream contents, or
null if the stream isnull .
-
toHex2
Converts the specified number into a 2 hexadecimal characters.- Parameters:
num- The number to convert to hex.- Returns:
- A
containing the specified characters.char [2]
-
toHex4
Converts the specified number into a 4 hexadecimal characters.- Parameters:
num- The number to convert to hex.- Returns:
- A
containing the specified characters.char [4] - Throws:
NumberFormatException- If the number is negative.
-
toHex8
Converts the specified number into a 8 hexadecimal characters.- Parameters:
num- The number to convert to hex.- Returns:
- A
containing the specified characters.char [8] - Throws:
NumberFormatException- If the number is negative.
-
toIsoDate
Converts the specified object to an ISO8601 date string.- Parameters:
c- The object to convert.- Returns:
- The converted object.
-
toIsoDateTime
Converts the specified object to an ISO8601 date-time string.- Parameters:
c- The object to convert.- Returns:
- The converted object.
-
toReadableBytes
Converts the specified bytes into a readable string.- Parameters:
b- The number to convert to hex.- Returns:
- A
containing the specified characters.char [2]
-
toSpacedHex
Same astoHex(byte[])but puts spaces between the byte strings.- Parameters:
bytes- The bytes to convert to hexadecimal.- Returns:
- A new string consisting of hexadecimal characters.
-
toString
Safely converts an object to a string, returningnull if the object isnull .- Parameters:
obj- The object to convert to a string.- Returns:
- The string representation of the object, or
null if the object isnull .
-
toString
Safely converts an object to a string, returning the default string if the object isnull .- Parameters:
obj- The object to convert to a string.defaultStr- The default string to return if the object isnull .- Returns:
- The string representation of the object, or the default string if the object is
null .
-
toStringArray
Converts a collection of strings to a string array.Returns
null if the collection isnull . Returns an empty array if the collection is empty.- Parameters:
collection- The collection to convert. Can benull .- Returns:
- A new string array containing the collection elements, or
null if the collection wasnull .
-
toUri
Converts the specified object to a URI.- Parameters:
o- The object to convert to a URI.- Returns:
- A new URI, or the same object if the object was already a URI, or
-
toUtf8
Converts the specified byte array to a UTF-8 string.- Parameters:
b- The byte array to convert.- Returns:
- The UTF-8 string representation, or
null if the array isnull .
-
toUtf8
Converts the contents of the specified input stream to a UTF-8 string.- Parameters:
is- The input stream to convert.- Returns:
- The UTF-8 string representation of the input stream contents, or
null if the stream isnull .
-
transliterate
Transliterates characters in a string by mapping characters from one set to another.Performs character-by-character translation. If a character is found in
fromChars , it is replaced with the corresponding character at the same position intoChars . Characters not found infromChars are left unchanged.Example:
transliterate(
"hello" ,"aeiou" ,"12345" );// "h2ll4" transliterate("ABC" ,"ABC" ,"XYZ" );// "XYZ" - Parameters:
str- The string to transliterate. Can benull .fromChars- The source character set. Can benull .toChars- The target character set. Can benull .- Returns:
- The transliterated string, or
null if input isnull . - Throws:
IllegalArgumentException- IffromChars andtoChars have different lengths.
-
trim
Same asString.trim()but preventsNullPointerExceptions .- Parameters:
s- The string to trim.- Returns:
- The trimmed string, or
null if the string wasnull .
-
trimEnd
Trims whitespace characters from the end of the specified string.- Parameters:
s- The string to trim.- Returns:
- The trimmed string, or
null if the string wasnull .
-
trimLeadingSlashes
Trims'/' characters from the beginning of the specified string.- Parameters:
s- The string to trim.- Returns:
- A new trimmed string, or the same string if no trimming was necessary.
-
trimSlashes
Trims'/' characters from both the start and end of the specified string.- Parameters:
s- The string to trim.- Returns:
- A new trimmed string, or the same string if no trimming was necessary.
-
trimSlashesAndSpaces
Trims'/' and space characters from both the start and end of the specified string.- Parameters:
s- The string to trim.- Returns:
- A new trimmed string, or the same string if no trimming was necessary.
-
trimStart
Trims whitespace characters from the beginning of the specified string.- Parameters:
s- The string to trim.- Returns:
- The trimmed string, or
null if the string wasnull .
-
trimTrailingSlashes
Trims'/' characters from the end of the specified string.- Parameters:
s- The string to trim.- Returns:
- A new trimmed string, or the same string if no trimming was necessary.
-
uncapitalize
Uncapitalizes the first character of a string.Example:
uncapitalize(
null );// null uncapitalize("" );// "" uncapitalize("Hello" );// "hello" uncapitalize("hello" );// "hello" uncapitalize("HELLO" );// "hELLO" - Parameters:
str- The string to uncapitalize.- Returns:
- The string with the first character uncapitalized, or
null if input isnull .
-
unescapeChars
Removes escape characters from the specified characters.- Parameters:
s- The string to remove escape characters from.escaped- The characters escaped.- Returns:
- A new string if characters were removed, or the same string if not or if the input was
null .
-
unescapeHtml
Unescapes HTML entities in a string.Unescapes the following HTML entities:
"&" →'&' "<" →'<' ">" →'>' """ →'"' "'" or"'" →'\''
Example:
unescapeHtml(
"<script>" );// Returns: "<script>" - Parameters:
str- The string to unescape.- Returns:
- The unescaped string, or
null if input isnull .
-
unescapeXml
Unescapes XML entities in a string.Unescapes the following XML entities:
"&" →'&' "<" →'<' ">" →'>' """ →'"' "'" →'\''
Example:
unescapeXml(
"<tag>" );// Returns: "<tag>" - Parameters:
str- The string to unescape.- Returns:
- The unescaped string, or
null if input isnull .
-
unicodeSequence
Creates an escaped-unicode sequence (e.g."\\u1234" ) for the specified character.- Parameters:
c- The character to create a sequence for.- Returns:
- An escaped-unicode sequence.
-
upperCase
Null-safe convenience method forString.toUpperCase().Converts the string to uppercase if not null.
- Parameters:
s- The string to convert.- Returns:
- The uppercase string, or
null if the input wasnull . - See Also:
-
urlDecode
Decodes aapplication/x-www-form-urlencoded string usingUTF-8 encoding scheme.- Parameters:
s- The string to decode.- Returns:
- The decoded string, or
null if input isnull .
-
urlEncode
Encodes aapplication/x-www-form-urlencoded string usingUTF-8 encoding scheme.- Parameters:
s- The string to encode.- Returns:
- The encoded string, or
null if input isnull .
-
urlEncodeLax
Same asurlEncode(String)except only escapes characters that absolutely need to be escaped.- Parameters:
s- The string to escape.- Returns:
- The encoded string, or
null if input isnull .
-
urlEncodePath
Similar toURLEncoder.encode(String, String)but doesn't encode"/" characters.- Parameters:
o- The object to encode.- Returns:
- The URL encoded string, or
null if the object was null.
-
wordCount
Counts the number of words in a string.A word is defined as a sequence of one or more word characters (letters, digits, underscores) separated by non-word characters.
Example:
wordCount(
"Hello world" );// 2 wordCount("The quick brown fox" );// 4 wordCount("Hello, world! How are you?" );// 5 - Parameters:
str- The string to count words in. Can benull .- Returns:
- The number of words, or
0 if the string isnull or empty.
-
wrap
Wraps text to a specified line length.Wraps text by breaking at word boundaries (spaces). Words longer than the wrap length will be broken at the wrap length. Existing newlines are preserved.
Example:
wrap(
"hello world test" , 10);// "hello world\ntest" wrap(null , 10);// null - Parameters:
str- The string to wrap.wrapLength- The maximum line length (must be > 0).- Returns:
- The wrapped string, or
null if input isnull . - Throws:
IllegalArgumentException- if wrapLength is <= 0.
-
wrap
Wraps text to a specified line length with a custom newline string.Wraps text by breaking at word boundaries (spaces). Words longer than the wrap length will be broken at the wrap length. Existing newlines are preserved.
Example:
wrap(
"hello world test" , 10," );
"// "hello world wrap(
test"null , 10,"\n" );// null - Parameters:
str- The string to wrap.wrapLength- The maximum line length (must be > 0).newline- The string to use as line separator.- Returns:
- The wrapped string, or
null if input isnull . - Throws:
IllegalArgumentException- if wrapLength is <= 0 or newline isnull .
-
isValidIPv6Address
Validates if a string is a valid IPv6 address format (without network operations).This method performs pure string-based validation and does not perform any DNS lookups or network operations, making it fast and suitable for validation purposes.
- Parameters:
ip- The IPv6 address string to validate.- Returns:
true if the string is a valid IPv6 address format,false otherwise.
-
skipComments
Skips over a single comment sequence in a StringReader.The reader must be positioned at the first
'/' character of a comment. This method will skip only the comment it's currently positioned on, not all comments in the reader.Supports both
"/* * /" style block comments and"//" style line comments.- Parameters:
r- The StringReader positioned at the start of a comment (at the first'/' ).- Throws:
IOException- If an I/O error occurs.
-