Class StringHelper


  • public class StringHelper
    extends Object
    Helper class for strings
    • Constructor Detail

      • StringHelper

        public StringHelper()
    • Method Detail

      • anyLineMatches

        public static boolean anyLineMatches​(String string,
                                             boolean supportsComments,
                                             Predicate<String> predicate)
        Returns whether at least one line matches the given predicate. If supportsComments is true, lines starting with # are ignored
      • areAllBlanks

        public static boolean areAllBlanks​(Object... elements)
        Returns true if all elements are blanks, otherwise false. Applies isNotBlank(Object) to all elements to know if at least one element is not blank.
      • areAllNotBlanks

        public static boolean areAllNotBlanks​(Object... elements)
        Returns true if all elements are not blanks, otherwise false. Applies isBlank(Object) to all elements to know if at least one element is blank. Warning do not confuse with areNotAllBlanks(Object...) (this is not the negation)
      • asciiOnly

        public static String asciiOnly​(String string)
        Removes from the given string all non-ASCII characters, returning null if the input is null
      • camelize

        public static String camelize​(String string)
        Transforms the given string into camel case. Examples:
        • camelize(null) == null
        • camelize("") == ""
        • camelize("MY_NAME") == "myName"
        • camelize("MyName") == "myname"
      • capitalize

        public static String capitalize​(String string)
        Returns a string where the first letter is uppercase and all others are lowercase
      • capitalizeAndCamelize

        public static String capitalizeAndCamelize​(String string)
      • capitalizeFirst

        public static String capitalizeFirst​(String string)
        Transforms the first character of the given string to upper case, handling nulls / empty strings
      • containsIgnoreCase

        public static boolean containsIgnoreCase​(String str,
                                                 String searchStr)
        Copied from Apache Commons Lang 3
      • convertNewLineToBr

        public static String convertNewLineToBr​(String string)
      • decodeQueryParameters

        public static Map<String,​String> decodeQueryParameters​(String query)
        Returns a set of parameters like application/x-www-form-urlencoded. Returns an empty string for null / empty parameters. If the given string starts with either '?', ';' or '#', the first character is ignored. When the same parameter is specified multiple times, join the values with a comma.
      • decodeURIComponent

        public static String decodeURIComponent​(String component)
        Translates a string back from application/x-www-form-urlencoded format using UTF-8 as the encoding scheme
      • defaultValue

        public static String defaultValue​(String string,
                                          String defaultValue)
        Returns the value of the second string if the first is blank. Otherwise, returns the first
        See Also:
        isBlank(Object)
      • delimit

        public static String delimit​(String text,
                                     String delimiter,
                                     int delimitSize)
        Transforms the given text adding a delimiter every time delimit size is reached.
        Example:
        • delimit("helloworld", ";", 2) == "he;ll;ow;or;ld"
      • emptyIfNull

        public static String emptyIfNull​(String s)
        Returns an empty string ("") when the parameter value is null. Otherwise, returns the parameter value.
      • encodeURIComponent

        public static String encodeURIComponent​(String component)
        Translates a string into application/x-www-form-urlencoded format using UTF-8 as the encoding scheme
      • forEachLine

        public static void forEachLine​(String string,
                                       boolean supportsComments,
                                       Consumer<String> consumer)
        Calls the given procedure for each non-empty untils the last line, trimmed line of the given string. If supportsComments is true, lines starting with # are ignored
      • forEachLine

        public static void forEachLine​(String string,
                                       boolean supportsComments,
                                       Predicate<String> predicate)
        Calls the given function for each non-empty while it return true, trimmed line of the given string. If supportsComments is true, lines starting with # are ignored
      • formatNumber

        public static String formatNumber​(String mask,
                                          String number,
                                          boolean padLeftWithZeros)
        Replaces the sharps in the mask by the digits found in the number. If padLeftWithZeros is true, replaces the extra front sharps with zeros.
      • getNumberGenerationPattern

        public static String getNumberGenerationPattern​(String prefix,
                                                        Integer padLength,
                                                        String suffix)
        Returns a pattern which may be used to filter user input based on a transaction number pattern
      • htmlSpace

        public static String htmlSpace()
        Returns the String representing an HTML space
      • htmlSpaces

        public static String htmlSpaces​(int count)
        Returns the String representing n HTML spaces
      • indexOf

        public static int indexOf​(String[] array,
                                  String stringToSearch)
        It returns the index of the first occurrence of the string in the array. Otherwise it returns -1. Null strings are supported and the index of the first null element in the array is returned (if any).
      • indexOfAny

        public static int indexOfAny​(String str,
                                     String possibleChars)
        Returns the first index of any of the given chars
      • indexOfAny

        public static int indexOfAny​(String str,
                                     String possibleChars,
                                     int fromIndex)
        Returns the first index of any of the given chars after the given index
      • isBlank

        public static boolean isBlank​(Object object)
        Use the object's toString() method and checks whether it is null, empty or blank string (spaces only)
      • isEquals

        public static boolean isEquals​(String value1,
                                       String value2)
        Returns true value1 is equals to value2 or both are empty
      • isNotBlank

        public static boolean isNotBlank​(Object object)
        Equivalent to the negation of isBlank(Object)
      • isNumeric

        public static boolean isNumeric​(String text)
        Returns true if the given string is not null and composed of numbers only
      • join

        public static String join​(Collection<?> parts,
                                  String delimiter)
        Join the array of strings with the given delimiter
      • join

        public static String join​(Object[] parts,
                                  String delimiter)
        Join the array of strings with the given delimiter
      • leftPad

        public static String leftPad​(String input,
                                     int size,
                                     char padChar)
        Left pad the specified input String until the specific pad size with the specified char.
        If input is null then it returns null.
      • lowercaseFirst

        public static String lowercaseFirst​(String string)
        Sets the first character as lower case. Examples:
        • lowercaseFirst(null) == null
        • lowercaseFirst("") == ""
        • lowercaseFirst("MY_NAME") == "mY_NAME"
        • lowercaseFirst("MyName") == "myName"
      • maskDigits

        public static String maskDigits​(String number,
                                        int plainLength)
        Returns a string with a all numbers replaced to *, except a few digits in the end. Example: maskDigits("1234-5678-9876", 4) = "****-****-9876"
      • maskEmail

        public static String maskEmail​(String email)
        Applies a mask to a given e-mail address
      • maskPhone

        public static String maskPhone​(String number)
        Applies a mask to a given phone number
      • numbersOnly

        public static String numbersOnly​(String string)
        Returns only the numbers of the given string. Never returns null.
      • phoneNumbersMatch

        public static boolean phoneNumbersMatch​(String number1,
                                                String number2)
        Returns whether 2 phone numbers match by suffix
      • random

        public static String random​(String allowed,
                                    int length)
        Returns a random string with the given size, comprised of the given allowed characters
      • randomAlphabetic

        public static String randomAlphabetic​(int length)
        Returns a random string with the given size, comprised of letters
      • randomAlphanumeric

        public static String randomAlphanumeric​(int length)
        Returns a random string with the given size, comprised of letters and numbers
      • randomNumeric

        public static String randomNumeric​(int length)
        Returns a random string with the given size, comprised of numbers
      • removeEnd

        public static String removeEnd​(String string,
                                       String end)
        Removes the end of the given string, or returns the original string if end is null or not the final part of the string
        • removeEnd(null, *) == null
        • removeEnd(x, *) == x
        • removeEnd("car", "ar") == "c"
        • removeEnd("car", "r") == "ca"
        • removeEnd("car", "x") == "car"
      • removeMarkupTags

        public static String removeMarkupTags​(String string)
        Removes all html/xml tags, keeping br tags as line breaks
      • removeMarkupTags

        public static String removeMarkupTags​(String string,
                                              boolean includeNL)
        Removes all html/xml tags and entities, keeping br tags as line breaks
      • removeNonAlpha

        public static String removeNonAlpha​(String string)
        Removes any character from the given string which is neither a digit nor a letter
      • removeScripts

        public static String removeScripts​(String value)
        Removes all <script> tags from the given string
      • removeStart

        public static String removeStart​(String string,
                                         String start)
        Removes the start of the given string, or returns the original string if end is null or not the initial part of the string
        • removeStart(null, *) == null
        • removeStart(x, *) == x
        • removeStart("car", "ca") == "r"
        • removeStart("car", "c") == "ar"
        • removeStart("car", "x") == "car"
      • repeat

        public static String repeat​(String string,
                                    int times)
        Repeats the given string the given number of times
      • replace

        public static String replace​(String text,
                                     String repl,
                                     String with)
        Replaces all occurrences of the source text with the destination text in the given string
      • replace

        public static String replace​(String text,
                                     String repl,
                                     String with,
                                     int max)
        Replaces a specified number of occurrences (-1 means unlimited) of the source text with the destination text in the given string
      • replacePeriod

        public static String replacePeriod​(String value)
        Replaces the normal 'Full Stop' char (U+002E, i.e period in North American English) by a 'One Dot Leader' char (U+2024).
        This utility method was created to prevent some email clients (e.g GMail) to auto-link the user's name (CYCLOS-10201). Although we already have a validation to avoid URLs in the user's name, the library we use for such validation doesn't detect site.com as a URL allowing saving a user, but GMail does auto-link it anyway (it shouldn't, but what can we do... dad G is dad G ;) )
      • replaceVariables

        public static String replaceVariables​(String template,
                                              Function<String,​?> resolver)
        Replaces variables in the form {varname} with the ones produced by the given function. The function receives the variable name and should return the corresponding value. If the function return value is null, an empty string is used instead.
      • replaceVariables

        public static String replaceVariables​(String template,
                                              Map<String,​?> variables)
        Replaces variables in the form {varname} with the ones in the map. If a variable is not present on the map, it is replaced with an empty string
      • right

        public static String right​(String string,
                                   int size)
        Returns the suffix of the given string with the given size. If the string is shorter than that size, returns empty. Returns null for null input.
      • safeFilename

        public static String safeFilename​(String text)
        Makes the given text safe for being used on filenames. Replaces any special characters by '_', but doesn't return multiple '_' in sequence. Example: "This.'is/a/\\text" results in "This_is_a_text".
      • score

        public static float score​(String filter,
                                  List<String> texts,
                                  Function<String,​String> preprocess)
        Returns a score which indicates how well a set of texts match the given filter. The order of the texts is important: It will have a higher score if it matches the first text. Note: This is currently a very simple algorithm: It just uses containsIgnoreCase(String, String). Returning 0 means no match. Returning > 0 means some match. When the filter is blank, returns a non-zero result, indicating that all pass.
      • shuffle

        public static void shuffle​(StringBuilder sb,
                                   Random rnd)
        Shuffles the characters of the given string builder
      • split

        public static List<String> split​(String input,
                                         String separator)
        Splits a string into an array according to the char specified as separator.
        Parameters:
        input - the string to split. If it's null/empty then the return is an empty list.
      • splitPreserveAllTokens

        public static String[] splitPreserveAllTokens​(String str,
                                                      String separatorChars)

        Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators. This is an alternative to using StringTokenizer.

        The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.

        A null input String returns null. A null separatorChars splits on whitespace.

      • suffixesEqual

        public static boolean suffixesEqual​(String s1,
                                            String s2,
                                            int size)
        Returns whether the suffix with a given size is the same on both strings
      • transformCase

        public static String transformCase​(String string,
                                           boolean toUpperCase,
                                           char separator)
        Transforms the given string into upper or lower case, adding the given separator between words. Examples:
        • transformCase(null, *, *) == null
        • transformCase("", *, *) == ""
        • transformCase("myName", true, '_') == "MY_NAME"
        • transformCase("MyName", true, '_') == "MY_NAME"
        • transformCase("MyNAME", true, '_') == "MY_N_A_M_E"
        • transformCase("myName", false, '-') == "my-name"
        • transformCase("MyName", false, '-') == "my-name"
        • transformCase("MyNAME", false, '-') == "my-n-a-m-e"
      • trim

        public static String trim​(Object value)
        Use the object's toString() method, trimming the result and returning the string. Never returns null values
      • trimToNull

        public static String trimToNull​(Object value)
        Same as trim(Object), but returning null instead of empty strings
      • truncate

        public static String truncate​(String string,
                                      int maxLength)
        Truncates the given string without cutting words in the middle, and appending ellipsis in the end. Line breaks are transformed in spaces.
      • truncateLines

        public static String truncateLines​(String string,
                                           int maxLines,
                                           int maxLengthPerLine)
        Truncates the given string to a maximum of lines, making each line have a maximum of characters. Empty lines are ignored.
      • unaccent

        public static String unaccent​(String string)
        Replaces any accented characters by the nearest unaccented character, returning null if the input is null. For example, áèïôçñ resuçts in aeiocn
      • uncapitalizeFirst

        public static String uncapitalizeFirst​(String string)
        Transforms the first character of the given string to lower case, handling nulls / empty strings
      • urlEncode

        public static String urlEncode​(Map<String,​?> params)
        Returns a set of parameters like application/x-www-form-urlencoded. Returns an empty string for null / empty parameters.
      • wrap

        public static String wrap​(String text,
                                  int wrapLength)
        Wraps a multi-line text to not break words.
        Long word are not wrapped and a "\n" is inserted for each new line that must need to be created.