Class StringUtils

java.lang.Object
org.apache.juneau.commons.utils.StringUtils

public class StringUtils extends Object
Reusable string utility methods.
  • Field Details

  • Constructor Details

  • Method Details

    • abbreviate

      public static String abbreviate(String in, int length)
      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 exactly length characters (including the ellipses).

      If the string is null, shorter than or equal to length, 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 be null.
      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

      public static StringBuilder append(StringBuilder sb, String in)
      Appends a string to a StringBuilder, creating a new one if null.
      Parameters:
      sb - The StringBuilder to append to, or null 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. If sb is null 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 StringBuilder sb2 = appendIfNotBlank(null, "test"); // Creates new StringBuilder with "test" StringBuilder sb3 = appendIfNotBlank(null, " "); // Returns null (no append occurred)

      Parameters:
      sb - The StringBuilder to append to. Can be null.
      str - The string to append if not blank. Can be null.
      Returns:
      The same StringBuilder instance for method chaining, or a new StringBuilder if sb was null and an append occurred, or null if sb was null 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. If sb is null 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 StringBuilder sb2 = appendIfNotEmpty(null, "test"); // Creates new StringBuilder with "test" StringBuilder sb3 = appendIfNotEmpty(null, null); // Returns null (no append occurred)

      Parameters:
      sb - The StringBuilder to append to. Can be null.
      str - The string to append if not empty. Can be null.
      Returns:
      The same StringBuilder instance for method chaining, or a new StringBuilder if sb was null and an append occurred, or null if sb was null and no append occurred.
    • appendWithSeparator

      public static StringBuilder appendWithSeparator(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.

      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 is null 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 StringBuilder sb2 = appendWithSeparator(null, "test", ", "); // Creates new StringBuilder with "test" StringBuilder sb3 = appendWithSeparator(null, null, ", "); // Returns null (no append occurred)

      Parameters:
      sb - The StringBuilder to append to. Can be null.
      str - The string to append. Can be null.
      separator - The separator to add before the string if the StringBuilder is not empty. Can be null.
      Returns:
      The same StringBuilder instance for method chaining, or a new StringBuilder if sb was null and an append occurred, or null if sb was null and no append occurred.
    • articlized

      public static String articlized(String subject)
      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

      public static byte[] base64Decode(String in)
      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

      public static String base64DecodeToString(String in)
      Shortcut for calling base64Decode(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

      public static String base64Encode(byte[] in)
      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

      public static String base64EncodeToString(String in)
      Shortcut for calling base64Encode(in.getBytes("UTF-8"))
      Parameters:
      in - The input string to convert.
      Returns:
      The string converted to BASE-64 encoding.
    • buildString

      public static String buildString(Consumer<StringBuilder> builder)
      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" String joined = 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 - If builder is null.
    • camelCase

      public static String camelCase(String str)
      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 is null.
    • capitalize

      public static String capitalize(String str)
      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 is null.
    • cdlToList

      public static List<String> cdlToList(String s)
      Converts a comma-delimited string to a list.
      Parameters:
      s - The comma-delimited string.
      Returns:
      A new modifiable list. Never null.
    • cdlToSet

      public static LinkedHashSet<String> cdlToSet(String s)
      Converts a comma-delimited string to a set.
      Parameters:
      s - The comma-delimited string.
      Returns:
      A new LinkedHashSet. Never null.
    • charAt

      public static char charAt(String s, int i)
      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). Returns 0 (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 is null.
      See Also:
    • clean

      public static String clean(String str)
      Cleans a string by removing control characters and normalizing whitespace.
      Example:

      clean("helloworld"); // "hello world" clean("hello \t\n world"); // "hello world"

      Parameters:
      str - The string to clean.
      Returns:
      The cleaned string, or null if input is null.
    • compare

      public static int compare(String s1, String s2)
      Compares two strings lexicographically, but gracefully handles null values.

      Null handling:

      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:
    • compareIgnoreCase

      public static int compareIgnoreCase(String str1, String str2)
      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

      public static byte[] compress(String contents) throws Exception
      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 String decompressed = 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

      public static boolean contains(String s, char c)
      Checks if a string contains the specified character.

      This is a null-safe operation. Returns false if the string is null.

      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

      public static boolean contains(String value, CharSequence substring)
      Null-safe String.contains(CharSequence) operation.

      Returns false if the string is null, otherwise behaves the same as String.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 is null.
      See Also:
    • contains

      public static boolean contains(String s, String substring)
      Null-safe check if a string contains another string.

      Returns false if the string is null, otherwise behaves the same as String.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 is null.
      See Also:
    • containsAll

      public static boolean containsAll(String s, char... values)
      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:
    • containsAll

      public static boolean containsAll(String s, CharSequence... values)
      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:
    • containsAll

      public static boolean containsAll(String s, String... values)
      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:
    • containsAny

      public static boolean containsAny(String s, char... values)
      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:
    • containsAny

      public static boolean containsAny(String s, CharSequence... values)
      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:
    • containsAny

      public static boolean containsAny(String s, String... values)
      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:
    • containsIgnoreCase

      public static boolean containsIgnoreCase(String str, String search)
      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

      public static int countChars(String s, char c)
      Counts the number of occurrences of the specified character in the specified string.

      Returns 0 if the string is null.

      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 was null.
    • countMatches

      public static int countMatches(String str, String search)
      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 is null or empty.
    • decodeHex

      public static String decodeHex(String s)
      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("HelloWorld"); // "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, or null if input is null.
    • decompress

      public static String decompress(byte[] is) throws Exception
      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 String decompressed = 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

      public static String defaultIfBlank(String str, String defaultStr)
      Returns the specified string, or the default string if that string is null or blank.
      Parameters:
      str - The string value to check.
      defaultStr - The default string to return if the string is null or blank.
      Returns:
      The string value, or the default string if the string is null or blank.
    • defaultIfEmpty

      public static String defaultIfEmpty(String str, String defaultStr)
      Returns the specified string, or the default string if that string is null or empty.
      Parameters:
      str - The string value to check.
      defaultStr - The default string to return if the string is null or empty.
      Returns:
      The string value, or the default string if the string is null or empty.
    • diffPosition

      public static int diffPosition(String s1, String s2)
      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

      public static int diffPositionIc(String s1, String s2)
      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

      public static String[] distinct(String[] array)
      Removes duplicate elements from a string array, preserving order.

      Returns null if the array is null. Uses a LinkedHashSet to 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 be null.
      Returns:
      A new array with duplicate elements removed, or null if the array was null.
    • doubleMetaphone

      public static String[] doubleMetaphone(String str)
      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 be null.
      Returns:
      An array with two elements: [primary code, alternate code]. Returns null if input is null or empty.
    • emptyIfNull

      public static String emptyIfNull(String str)
      Returns the specified string, or an empty string if that string is null.
      Parameters:
      str - The string value to check.
      Returns:
      The string value, or an empty string if the string is null.
    • endsWith

      public static boolean endsWith(String s, char c)
      Checks if a string ends with the specified character.

      This is a null-safe operation. Returns false if the string is null 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 be null.
      c - The character to check for.
      Returns:
      true if the specified string is not null and ends with the specified character.
      See Also:
    • endsWith

      public static boolean endsWith(String s, String suffix)
      Checks if a string ends with the specified string.

      This is a null-safe operation. Returns false if the string is null. Otherwise behaves the same as String.endsWith(String).

      Example:

      endsWith("Hello World", "World"); // true endsWith("Hello World", "Hello"); // false endsWith(null, "World"); // false

      Parameters:
      s - The string to check. Can be null.
      suffix - The suffix to check for.
      Returns:
      true if the string ends with the specified suffix.
      See Also:
    • endsWithAny

      public static boolean endsWithAny(String s, char... c)
      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 be null.
      c - The characters to check for.
      Returns:
      true if the string ends with any of the specified characters.
      See Also:
    • endsWithAny

      public static boolean endsWithAny(String s, String... suffixes)
      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 be null.
      suffixes - The suffixes to check for.
      Returns:
      true if the string ends with any of the specified suffixes.
      See Also:
    • endsWithIgnoreCase

      public static boolean endsWithIgnoreCase(String str, String suffix)
      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

      public static double entropy(String str)
      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 be null.
      Returns:
      The entropy value (0.0 or higher), or 0.0 if the string is null or empty.
    • equalsIgnoreCase

      public static boolean equalsIgnoreCase(Object a, Object b)
      Tests two objects for case-insensitive string equality.

      Converts both objects to strings using Object.toString() before comparison. This method handles null values gracefully:

      • Both null → returns true
      • One null → returns false
      • 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:
    • equalsIgnoreCase

      public static boolean equalsIgnoreCase(String str1, String str2)
      Tests two strings for case-insensitive equality, but gracefully handles nulls.

      This method handles null values gracefully:

      • Both null → returns true (same reference check)
      • One null → returns false
      • 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:
    • escapeChars

      public static String escapeChars(String s, AsciiSet escaped)
      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

      public static String escapeForJava(String s)
      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 is null.
    • escapeHtml

      public static String escapeHtml(String str)
      Escapes HTML entities in a string.

      Escapes the following characters:

      • '&'"&amp;"
      • '<'"&lt;"
      • '>'"&gt;"
      • '"'"&quot;"
      • '\''"&#39;"
      Example:

      escapeHtml("<script>alert('xss')</script>"); // Returns: "&lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;"

      Parameters:
      str - The string to escape.
      Returns:
      The escaped string, or null if input is null.
    • escapeRegex

      public static String escapeRegex(String str)
      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 is null.
    • escapeSql

      public static String escapeSql(String str)
      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 is null.
    • escapeXml

      public static String escapeXml(String str)
      Escapes XML entities in a string.

      Escapes the following characters:

      • '&'"&amp;"
      • '<'"&lt;"
      • '>'"&gt;"
      • '"'"&quot;"
      • '\''"&apos;"
      Example:

      escapeXml("<tag attr='value'>text</tag>"); // Returns: "&lt;tag attr=&apos;value&apos;&gt;text&lt;/tag&gt;"

      Parameters:
      str - The string to escape.
      Returns:
      The escaped string, or null if input is null.
    • extractBetween

      public static List<String> extractBetween(String str, String start, String end)
      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 be null.
      start - The start marker. Can be null.
      end - The end marker. Can be null.
      Returns:
      A list of text segments found between the markers, or an empty list if any parameter is null or empty.
    • extractEmails

      public static List<String> extractEmails(String str)
      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 be null.
      Returns:
      A list of email addresses found in the input, or an empty list if the string is null or empty.
    • extractNumbers

      public static List<String> extractNumbers(String str)
      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 be null.
      Returns:
      A list of numeric strings found in the input, or an empty list if the string is null or empty.
    • extractUrls

      public static List<String> extractUrls(String str)
      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 be null.
      Returns:
      A list of URLs found in the input, or an empty list if the string is null or empty.
    • extractWords

      public static List<String> extractWords(String str)
      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 be null.
      Returns:
      A list of words found in the input, or an empty list if the string is null or empty.
    • filter

      public static String[] filter(String[] array, Predicate<String> predicate)
      Filters a string array using the specified predicate.

      Returns null if the array is null. Returns an empty array if the predicate is null 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 be null.
      predicate - The predicate to apply to each element. Can be null.
      Returns:
      A new array containing only the elements that match the predicate, or null if the array was null.
    • firstChar

      public static char firstChar(String s)
      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 is null or empty.
      See Also:
    • firstNonBlank

      public static String firstNonBlank(String... vals)
      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 or null.
    • firstNonEmpty

      public static String firstNonEmpty(String... s)
      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 by Utils.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 all null or empty.
      See Also:
    • firstNonWhitespaceChar

      public static char firstNonWhitespaceChar(String s)
      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 is null, empty, or composed of only whitespace.
      See Also:
    • fixUrl

      public static String fixUrl(String in)
      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 be null.
      Returns:
      The URI with invalid characters encoded, or null if input is null.
      See Also:
    • format

      public static String format(String pattern, Object... args)
      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's String.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 a NullPointerException for numeric conversions (consistent with String.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:
    • formatNamed

      public static String formatNamed(String s, Map<String,Object> m)
      Simple utility for replacing variables of the form "{key}" with values in the specified map.

      Supports named MessageFormat-style variables: "{key}" where key is a map key. For un-numbered sequential placeholders "{}", use format(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

      public static byte[] fromHex(String hex)
      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

      public static String fromHexToUTF8(String hex)
      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

      public static byte[] fromSpacedHex(String hex)
      Same as fromHex(String) except expects spaces between the byte strings.
      Parameters:
      hex - The string to convert to a byte array.
      Returns:
      A new byte array.
    • fromSpacedHexToUTF8

      public static String fromSpacedHexToUTF8(String hex)
      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

      public static 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

      public static String getAuthorityUri(String s)
      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

      public static long getDuration(String s)
      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 or null.
    • getGlobMatchPattern

      public static Pattern getGlobMatchPattern(String s)
      Converts a string containing glob-style wildcard characters to a regular expression Pattern.

      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 Pattern object, or null if the input string is null.
    • getGlobMatchPattern

      public static Pattern getGlobMatchPattern(String s, int flags)
      Converts a string containing glob-style wildcard characters to a regular expression Pattern with 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

      Parameters:
      s - The glob-style wildcard pattern string.
      flags - Regular expression flags (see Pattern constants).
      Returns:
      A compiled Pattern object, or null if the input string is null.
    • getMatchPattern

      public static Pattern getMatchPattern(String s)
      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

      public static Pattern getMatchPattern(String s, int flags)
      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

      public static String getNumberedLines(String s)
      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

      public static String getNumberedLines(String s, int start, int end)
      Same as getNumberedLines(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

      public static long getStringSize(String str)
      Calculates the approximate memory size of a string in bytes.

      Returns 0 if the input string is null. 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 be null.
      Returns:
      The approximate memory size in bytes, or 0 if the input was null.
    • hasText

      public static boolean hasText(String str)
      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

      public static int indexOf(String s, char... c)
      Same as String.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

      public static int indexOf(String str, String search)
      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 is null.
    • indexOfIgnoreCase

      public static int indexOfIgnoreCase(String str, String search)
      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 is null.
    • intern

      public static String intern(String str)
      Interns a string, returning the canonical representation.

      Returns null if the input string is null. This method provides a null-safe wrapper around String.intern().

      Examples:

      String s1 = new String("test"); String s2 = new String("test"); assertTrue(s1 != s2); // Different objects String i1 = intern(s1); String i2 = 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 be null.
      Returns:
      The interned string, or null if the input was null.
    • interpolate

      public static String interpolate(String template, Map<String,Object> variables)
      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

      public static boolean isAbsoluteUri(String s)
      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

      public static boolean isAllNotBlank(CharSequence... values)
      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. Returns false 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

      public static boolean isAllNotEmpty(CharSequence... values)
      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. Returns false 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

      public static boolean isAlpha(String str)
      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

      public static boolean isAlphaNumeric(String str)
      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

      public static boolean isAnyNotBlank(CharSequence... values)
      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

      public static boolean isAnyNotEmpty(CharSequence... values)
      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

      public static boolean isBlank(CharSequence str)
      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

      public static boolean isCreditCard(String str)
      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

      public static boolean isDecimal(String s)
      Returns true if the specified string is numeric.
      Parameters:
      s - The string to check.
      Returns:
      true if the specified string is numeric.
    • isDigit

      public static boolean isDigit(String str)
      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

      public static boolean isEmail(String str)
      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

      public static boolean isEmpty(String str)
      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

      public static boolean isFirstNumberChar(char c)
      Returns true 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

      public static boolean isFloat(String s)
      Returns true 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

      public static boolean isInterned(String str)
      Checks if a string is already interned.

      Returns false if the input string is null. 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)); String s2 = new String("test"); // New object, not interned assertFalse(isInterned(s2)); String s3 = intern(s2); // Now interned assertTrue(isInterned(s3));

      Parameters:
      str - The string to check. Can be null.
      Returns:
      true if the string is interned, false otherwise.
    • isProbablyJson

      public static boolean isProbablyJson(String s)
      Returns true 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

      public static boolean isProbablyJsonArray(Object o, boolean ignoreWhitespaceAndComments)
      Returns true 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 - If true, leading and trailing whitespace and comments will be ignored.
      Returns:
      true if the specified string appears to be a JSON array.
    • isProbablyJsonObject

      public static boolean isProbablyJsonObject(Object o, boolean ignoreWhitespaceAndComments)
      Returns true 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 - If true, leading and trailing whitespace and comments will be ignored.
      Returns:
      true if the specified string appears to be a JSON object.
    • isNotBlank

      public static boolean isNotBlank(CharSequence str)
      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

      public static boolean isNumberChar(char c)
      Returns true 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

      public static boolean isNumeric(String s)
      Returns true if this string can be parsed by parseNumber(String, Class).
      Parameters:
      s - The string to check.
      Returns:
      true if this string can be parsed without causing an exception.
    • isOneOf

      public static boolean isOneOf(String s, String... values)
      Returns true if the specified string is one of the specified values.
      Parameters:
      s - The string to test. Can be null.
      values - The values to test. Can contain null.
      Returns:
      true if the specified string is one of the specified values.
    • isPhoneNumber

      public static boolean isPhoneNumber(String str)
      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.
    • isSimilar

      public static boolean isSimilar(String str1, String str2, double threshold)
      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

      public static boolean isUri(String s)
      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

      public static boolean isValidDateFormat(String dateStr, String format)
      Validates if a date string matches the specified date format.

      Uses SimpleDateFormat to 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 be null.
      format - The date format pattern (e.g., "yyyy-MM-dd"). Can be null.
      Returns:
      true if the date string matches the format, false otherwise.
    • isValidHostname

      public static boolean isValidHostname(String hostname)
      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 be null.
      Returns:
      true if the string is a valid hostname, false otherwise.
    • isValidIpAddress

      public static boolean isValidIpAddress(String ip)
      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 be null.
      Returns:
      true if the string is a valid IP address, false otherwise.
    • isValidMacAddress

      public static boolean isValidMacAddress(String mac)
      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 be null.
      Returns:
      true if the string is a valid MAC address, false otherwise.
    • isValidRegex

      public static boolean isValidRegex(String regex)
      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 be null.
      Returns:
      true if the string is a valid regex pattern, false otherwise.
    • isValidTimeFormat

      public static boolean isValidTimeFormat(String timeStr, String format)
      Validates if a time string matches the specified time format.

      Uses SimpleDateFormat to 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 be null.
      format - The time format pattern (e.g., "HH:mm:ss"). Can be null.
      Returns:
      true if the time string matches the format, false otherwise.
    • isWhitespace

      public static boolean isWhitespace(int c)
      Checks if a character is whitespace.
      Parameters:
      c - The character to check.
      Returns:
      true if the character is whitespace.
    • isWhitespace

      public static boolean isWhitespace(String str)
      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

      public static String join(Collection<?> values)
      Combines collection values into a simple comma-delimited string.
      Parameters:
      values - The values to join.
      Returns:
      A comma-delimited string.
    • join

      public static String join(Collection<?> tokens, char d)
      Join the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • join

      public static String join(Collection<?> tokens, String d)
      Join the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • join

      public static StringBuilder join(Collection<?> tokens, String d, StringBuilder sb)
      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

      public static String join(int[] tokens, char d)
      Join the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • join

      public static String join(int[] array, String delimiter)
      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

      public static String join(Object[] tokens, char d)
      Joins the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • join

      public static StringBuilder join(Object[] tokens, char d, StringBuilder sb)
      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

      public static String join(Object[] tokens, String separator)
      Join the specified tokens into a delimited string.
      Parameters:
      tokens - The tokens to join.
      separator - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • join

      public static String join(String... values)
      Combines values into a simple comma-delimited string.
      Parameters:
      values - The values to join.
      Returns:
      A comma-delimited string.
    • joine

      public static String joine(List<?> tokens, char d)
      Same as join(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 is null, returns null.
    • joinnl

      public static String joinnl(Object[] tokens)
      Joins tokens with newlines.
      Parameters:
      tokens - The tokens to concatenate.
      Returns:
      A string with the specified tokens contatenated with newlines.
    • kebabCase

      public static String kebabCase(String str)
      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 is null.
    • lastIndexOf

      public static int lastIndexOf(String str, String search)
      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 is null.
    • lastIndexOfIgnoreCase

      public static int lastIndexOfIgnoreCase(String str, String search)
      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 is null.
    • lastNonWhitespaceChar

      public static char lastNonWhitespaceChar(String s)
      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 is null, empty, or composed of only whitespace.
    • left

      public static String left(String str, int len)
      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 is null.
    • levenshteinDistance

      public static int levenshteinDistance(String str1, String str2)
      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

      public static int lineCount(String str)
      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 be null.
      Returns:
      The number of lines, or 0 if the string is null or empty.
    • lowerCase

      public static String lowerCase(String s)
      Null-safe convenience method for String.toLowerCase().

      Converts the string to lowercase if not null.

      Parameters:
      s - The string to convert.
      Returns:
      The lowercase string, or null if the input was null.
      See Also:
    • mapped

      public static String[] mapped(String[] array, Function<String,String> mapper)
      Maps each element of a string array using the specified function.

      Returns null if the array is null. Returns an array with null elements if the function is null or returns null.

      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 be null.
      mapper - The function to apply to each element. Can be null.
      Returns:
      A new array with the mapped elements, or null if the array was null.
    • matches

      public static boolean matches(String str, String regex)
      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

      public static String metaphone(String str)
      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 be null.
      Returns:
      The Metaphone code, or null if input is null or empty.
    • mid

      public static String mid(String str, int pos, int len)
      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 is null.
    • mostFrequentChar

      public static char mostFrequentChar(String str)
      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 be null.
      Returns:
      The most frequent character, or '\0' if the string is null or empty.
    • naturalCompare

      public static int naturalCompare(String str1, String str2)
      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

      public static String normalizeUnicode(String str)
      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 be null.
      Returns:
      The normalized string, or null if input is null.
    • normalizeWhitespace

      public static String normalizeWhitespace(String str)
      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 is null.
    • notContains

      public static boolean notContains(String s, char c)
      Checks if a string does not contain the specified character.

      This is the inverse of contains(String, char). Returns true if the string is null 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

      public static boolean notContains(String s, CharSequence substring)
      Checks if a string does not contain the specified substring.

      This is the inverse of contains(String, CharSequence). Returns true if the string is null 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

      public static boolean notContains(String s, String substring)
      Checks if a string does not contain the specified substring.

      This is the inverse of contains(String, String). Returns true if the string is null 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

      public static boolean notContainsAll(String s, char... values)
      Checks if a string does not contain all of the specified characters.

      This is the inverse of containsAll(String, char...). Returns true 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:
    • notContainsAll

      public static boolean notContainsAll(String s, CharSequence... values)
      Checks if a string does not contain all of the specified substrings.

      This is the inverse of containsAll(String, CharSequence...). Returns true 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:
    • notContainsAll

      public static boolean notContainsAll(String s, String... values)
      Checks if a string does not contain all of the specified substrings.

      This is the inverse of containsAll(String, String...). Returns true 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:
    • notContainsAny

      public static boolean notContainsAny(String s, char... values)
      Checks if a string does not contain any of the specified characters.

      This is the inverse of containsAny(String, char...). Returns true 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:
    • notContainsAny

      public static boolean notContainsAny(String s, CharSequence... values)
      Checks if a string does not contain any of the specified substrings.

      This is the inverse of containsAny(String, CharSequence...). Returns true 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:
    • notContainsAny

      public static boolean notContainsAny(String s, String... values)
      Checks if a string does not contain any of the specified substrings.

      This is the inverse of containsAny(String, String...). Returns true 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:
    • obfuscate

      public static String obfuscate(String s)
      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

      public static String ordinal(int number)
      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

      public static String padCenter(String str, int size, char padChar)
      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

      public static String padLeft(String str, int size, char padChar)
      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

      public static String padRight(String str, int size, char padChar)
      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

      public static Character parseCharacter(Object o)
      Converts a String to a Character
      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 is null or empty.
      Throws:
      IllegalArgumentException - If the string length is not 1.
    • parseFloat

      public static float parseFloat(String value)
      Same as Float.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 is null.
    • parseInt

      public static int parseInt(String value)
      Same as Integer.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 is null.
    • parseIntWithSuffix

      public static int parseIntWithSuffix(String s)
      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

      public static long parseLong(String value)
      Same as Long.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 is null.
    • parseLongWithSuffix

      public static long parseLongWithSuffix(String s)
      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 be null.
      keyValueDelimiter - The character that separates keys from values.
      entryDelimiter - The character that separates entries.
      trimKeys - If true, 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

      public static Number parseNumber(String s, Class<? extends Number> type)
      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
      If null or Number, uses the best guess.
      Returns:
      The parsed number, or null if the string was null.
    • pascalCase

      public static String pascalCase(String str)
      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 is null.
    • pluralize

      public static String pluralize(String word, int count)
      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

      public static String random(int numchars)
      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

      public static String randomAlphabetic(int length)
      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

      public static String randomAlphanumeric(int length)
      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

      public static String randomAscii(int length)
      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

      public static String randomNumeric(int length)
      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

      public static String randomString(int length, String chars)
      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

      public static double readabilityScore(String str)
      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)
      Returns a score from 0-100, where higher scores indicate easier reading.
      Example:

      readabilityScore("The cat sat."); // Higher score (simple) readabilityScore("The sophisticated..."); // Lower score (complex)

      Parameters:
      str - The string to analyze. Can be null.
      Returns:
      A readability score from 0-100, or 0.0 if the string is null or empty.
    • readable

      public static String readable(Object o)
      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 be null.
      Returns:
      A readable string representation of the object, or null if the input was null.
    • remove

      public static String remove(String str, String 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 is null.
    • removeAccents

      public static String removeAccents(String str)
      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 be null.
      Returns:
      The string with accents removed, or null if input is null.
    • removeAll

      public static String removeAll(String str, String... remove)
      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 is null.
    • removeControlChars

      public static String removeControlChars(String str)
      Removes control characters from a string, replacing them with spaces.
      Example:

      removeControlChars("helloworld"); // "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 is null.
    • removeEnd

      public static String removeEnd(String str, String suffix)
      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 is null.
    • removeNonPrintable

      public static String removeNonPrintable(String str)
      Removes non-printable characters from a string.
      Example:

      removeNonPrintable("helloworld"); // "helloworld"

      Parameters:
      str - The string to process.
      Returns:
      The string with non-printable characters removed, or null if input is null.
    • removeStart

      public static String removeStart(String str, String prefix)
      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 is null.
    • removeUnderscores

      public static String removeUnderscores(String value)
      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 be null.
      Returns:
      A new string with all underscores removed, or the original string if it contains no underscores.
      Throws:
      IllegalArgumentException - If value is null.
      See Also:
    • repeat

      public static String repeat(int count, String pattern)
      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

      public static String reverse(String str)
      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 is null.
    • right

      public static String right(String str, int len)
      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 is null.
    • sanitize

      public static String sanitize(String str)
      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>"); // "&lt;script&gt;alert('xss')&lt;/script&gt;" sanitize("Hello <b>World</b>"); // "Hello &lt;b&gt;World&lt;/b&gt;"

      Parameters:
      str - The string to sanitize.
      Returns:
      The sanitized string with HTML/XML tags escaped, or null if input is null.
    • similarity

      public static double similarity(String str1, String str2)
      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

      public static String snakeCase(String str)
      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 is null.
    • sort

      public static String[] sort(String[] array)
      Sorts a string array in natural order.

      Returns null if the array is null. 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 be null.
      Returns:
      A new sorted array, or null if the array was null.
    • sortIgnoreCase

      public static String[] sortIgnoreCase(String[] array)
      Sorts a string array in case-insensitive order.

      Returns null if the array is null. 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 be null.
      Returns:
      A new sorted array (case-insensitive), or null if the array was null.
    • soundex

      public static String soundex(String str)
      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 be null.
      Returns:
      The Soundex code (1 letter + 3 digits), or null if input is null or empty.
    • split

      public static List<String> split(String s)
      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

      public static List<String> split(String s, char c)
      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 be null.
      c - The character to split on.
      Returns:
      The tokens, or null if the string was null.
    • split

      public static void split(String s, char c, Consumer<String> consumer)
      Same as splita(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

      public static List<String> split(String s, char c, int limit)
      Same as splita(java.lang.String) but limits the number of tokens returned.
      Parameters:
      s - The string to split. Can be null.
      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

      public static void split(String s, Consumer<String> consumer)
      Same as splita(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

      public static String[] splita(String s)
      Splits a comma-delimited list into an array of strings.
      Parameters:
      s - The string to split.
      Returns:
      An array of split strings.
    • splita

      public static String[] splita(String s, char c)
      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 be null.
      c - The character to split on.
      Returns:
      The tokens, or null if the string was null.
    • splita

      public static String[] splita(String s, char c, int limit)
      Same as splita(String, char) but limits the number of tokens returned.
      Parameters:
      s - The string to split. Can be null.
      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

      public static String[] splita(String[] s, char c)
      Same as splita(String, char) except splits all strings in the input and returns a single result.
      Parameters:
      s - The string to split. Can be null.
      c - The character to split on.
      Returns:
      The tokens, or null if the input array was null
    • splitMap

      public static Map<String,String> splitMap(String s, boolean trim)
      Splits a list of key-value pairs into an ordered map.

      Example:

      String in = "foo=1;bar=2"; Map map = 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

      public static String[] splitMethodArgs(String s)
      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

      public static List<String> splitNested(String s)
      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 was null.
      An empty string results in an empty array.
    • splitNestedInner

      public static List<String> splitNestedInner(String s)
      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 was null.
      An empty string results in an empty array.
    • splitQuoted

      public static String[] splitQuoted(String s)
      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 was null.
      An empty string results in an empty array.
    • splitQuoted

      public static String[] splitQuoted(String s, boolean keepQuotes)
      Same as splitQuoted(String) but allows you to optionally keep the quote characters.
      Parameters:
      s - The input string.
      keepQuotes - If true, quote characters are kept on the tokens.
      Returns:
      The results, or null if the input was null.
      An empty string results in an empty array.
    • startsWith

      public static boolean startsWith(String s, char c)
      An efficient method for checking if a string starts with a character.
      Parameters:
      s - The string to check. Can be null.
      c - The character to check for.
      Returns:
      true if the specified string is not null and starts with the specified character.
    • startsWithIgnoreCase

      public static boolean startsWithIgnoreCase(String str, String prefix)
      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

      public static Supplier<String> stringSupplier(Supplier<?> s)
      Takes a supplier of any type and returns a Supplier<String>.

      Useful when passing arguments to loggers.

      Parameters:
      s - The supplier.
      Returns:
      A string supplier that calls readable(Object) on the supplied value.
    • strip

      public static String strip(String s)
      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

      public static String substringAfter(String str, String separator)
      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

      public static String substringBefore(String str, String separator)
      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

      public static String substringBetween(String str, String open, String close)
      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

      public static String swapCase(String str)
      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 is null.
    • titleCase

      public static String titleCase(String str)
      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 is null.
    • toCdl

      public static String toCdl(Object o)
      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

      public static String toHex(byte b)
      Converts the specified byte into a 2 hexadecimal characters.
      Parameters:
      b - The number to convert to hex.
      Returns:
      A char[2] containing the specified characters.
    • toHex

      public static String toHex(byte[] bytes)
      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

      public static String toHex(InputStream is)
      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 is null.
    • toHex2

      public static char[] toHex2(int num)
      Converts the specified number into a 2 hexadecimal characters.
      Parameters:
      num - The number to convert to hex.
      Returns:
      A char[2] containing the specified characters.
    • toHex4

      public static char[] toHex4(int num)
      Converts the specified number into a 4 hexadecimal characters.
      Parameters:
      num - The number to convert to hex.
      Returns:
      A char[4] containing the specified characters.
      Throws:
      NumberFormatException - If the number is negative.
    • toHex8

      public static char[] toHex8(long num)
      Converts the specified number into a 8 hexadecimal characters.
      Parameters:
      num - The number to convert to hex.
      Returns:
      A char[8] containing the specified characters.
      Throws:
      NumberFormatException - If the number is negative.
    • toIsoDate

      public static String toIsoDate(Calendar c)
      Converts the specified object to an ISO8601 date string.
      Parameters:
      c - The object to convert.
      Returns:
      The converted object.
    • toIsoDateTime

      public static String toIsoDateTime(Calendar c)
      Converts the specified object to an ISO8601 date-time string.
      Parameters:
      c - The object to convert.
      Returns:
      The converted object.
    • toReadableBytes

      public static String toReadableBytes(byte[] b)
      Converts the specified bytes into a readable string.
      Parameters:
      b - The number to convert to hex.
      Returns:
      A char[2] containing the specified characters.
    • toSpacedHex

      public static String toSpacedHex(byte[] bytes)
      Same as toHex(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

      public static String toString(Object obj)
      Safely converts an object to a string, returning null if the object is null.
      Parameters:
      obj - The object to convert to a string.
      Returns:
      The string representation of the object, or null if the object is null.
    • toString

      public static String toString(Object obj, String defaultStr)
      Safely converts an object to a string, returning the default string if the object is null.
      Parameters:
      obj - The object to convert to a string.
      defaultStr - The default string to return if the object is null.
      Returns:
      The string representation of the object, or the default string if the object is null.
    • toStringArray

      public static String[] toStringArray(Collection<String> collection)
      Converts a collection of strings to a string array.

      Returns null if the collection is null. Returns an empty array if the collection is empty.

      Parameters:
      collection - The collection to convert. Can be null.
      Returns:
      A new string array containing the collection elements, or null if the collection was null.
    • toUri

      public static URI toUri(Object o)
      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

      public static String toUtf8(byte[] b)
      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 is null.
    • toUtf8

      public static String toUtf8(InputStream is)
      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 is null.
    • transliterate

      public static String transliterate(String str, String fromChars, String toChars)
      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 in toChars. Characters not found in fromChars are left unchanged.

      Example:

      transliterate("hello", "aeiou", "12345"); // "h2ll4" transliterate("ABC", "ABC", "XYZ"); // "XYZ"

      Parameters:
      str - The string to transliterate. Can be null.
      fromChars - The source character set. Can be null.
      toChars - The target character set. Can be null.
      Returns:
      The transliterated string, or null if input is null.
      Throws:
      IllegalArgumentException - If fromChars and toChars have different lengths.
    • trim

      public static String trim(String s)
      Same as String.trim() but prevents NullPointerExceptions.
      Parameters:
      s - The string to trim.
      Returns:
      The trimmed string, or null if the string was null.
    • trimEnd

      public static String trimEnd(String s)
      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 was null.
    • trimLeadingSlashes

      public static String trimLeadingSlashes(String s)
      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

      public static String trimSlashes(String s)
      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

      public static String trimSlashesAndSpaces(String s)
      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

      public static String trimStart(String s)
      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 was null.
    • trimTrailingSlashes

      public static String trimTrailingSlashes(String s)
      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

      public static String uncapitalize(String str)
      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 is null.
    • unescapeChars

      public static String unescapeChars(String s, AsciiSet escaped)
      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

      public static String unescapeHtml(String str)
      Unescapes HTML entities in a string.

      Unescapes the following HTML entities:

      • "&amp;"'&'
      • "&lt;"'<'
      • "&gt;"'>'
      • "&quot;"'"'
      • "&#39;" or "&apos;"'\''
      Example:

      unescapeHtml("&lt;script&gt;"); // Returns: "<script>"

      Parameters:
      str - The string to unescape.
      Returns:
      The unescaped string, or null if input is null.
    • unescapeXml

      public static String unescapeXml(String str)
      Unescapes XML entities in a string.

      Unescapes the following XML entities:

      • "&amp;"'&'
      • "&lt;"'<'
      • "&gt;"'>'
      • "&quot;"'"'
      • "&apos;"'\''
      Example:

      unescapeXml("&lt;tag&gt;"); // Returns: "<tag>"

      Parameters:
      str - The string to unescape.
      Returns:
      The unescaped string, or null if input is null.
    • unicodeSequence

      public static String unicodeSequence(char c)
      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

      public static String upperCase(String s)
      Null-safe convenience method for String.toUpperCase().

      Converts the string to uppercase if not null.

      Parameters:
      s - The string to convert.
      Returns:
      The uppercase string, or null if the input was null.
      See Also:
    • urlDecode

      public static String urlDecode(String s)
      Decodes a application/x-www-form-urlencoded string using UTF-8 encoding scheme.
      Parameters:
      s - The string to decode.
      Returns:
      The decoded string, or null if input is null.
    • urlEncode

      public static String urlEncode(String s)
      Encodes a application/x-www-form-urlencoded string using UTF-8 encoding scheme.
      Parameters:
      s - The string to encode.
      Returns:
      The encoded string, or null if input is null.
    • urlEncodeLax

      public static String urlEncodeLax(String s)
      Same as urlEncode(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 is null.
    • urlEncodePath

      public static String urlEncodePath(Object o)
      Similar to URLEncoder.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

      public static int wordCount(String str)
      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 be null.
      Returns:
      The number of words, or 0 if the string is null or empty.
    • wrap

      public static String wrap(String str, int wrapLength)
      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 is null.
      Throws:
      IllegalArgumentException - if wrapLength is <= 0.
    • wrap

      public static String wrap(String str, int wrapLength, String newline)
      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
      test"
      wrap(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 is null.
      Throws:
      IllegalArgumentException - if wrapLength is <= 0 or newline is null.
    • isValidIPv6Address

      public static boolean isValidIPv6Address(String ip)
      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

      public static void skipComments(StringReader r) throws IOException
      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.