Package jmri.util

Class StringUtil


  • public class StringUtil
    extends java.lang.Object
    Common utility methods for working with Strings.

    We needed a place to refactor common string-processing idioms in JMRI code, so this class was created. It's more of a library of procedures than a real class, as (so far) all of the operations have needed no state information.

    In some cases, these routines use a Java 1.3 or later method, falling back to an explicit implementation when running on Java 1.1

    • Constructor Summary

      Constructors 
      Constructor Description
      StringUtil()  
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static java.lang.String appendTwoHexFromInt​(int val, java.lang.String inString)
      Quickly append an integer to a String as exactly two hexadecimal characters
      static java.lang.String arrayToString​(byte[] v)
      Convert an array of bytes into a single string.
      static java.lang.String arrayToString​(int[] v)
      Convert an array of integers into a single string.
      static <E> java.lang.String arrayToString​(E[] v)
      Convert an array of objects into a single string.
      static byte[] bytesFromHexString​(java.lang.String s)
      Create a byte[] from a String containing hexadecimal values.
      static java.lang.String concatTextHtmlAware​(java.lang.String baseText, java.lang.String extraText)
      Concatenates text Strings where either could possibly be in HTML format (as used in many Swing components).
      static byte[] fullTextToHexArray​(java.lang.String s, int numBytes)
      Create a hex byte[] of Unicode character values from a String containing full text (non hex) values.
      static int getByte​(int b, java.lang.String byteString)
      Get a single hex data byte from a string
      static int getFirstIntFromString​(java.lang.String str)
      Return the first int value within a string eg :X X123XX456X: will return 123 eg :X123 456: will return 123
      static int getHexDigit​(int index, java.lang.String byteString)
      Get a single hex digit from a String.
      static int getLastIntFromString​(java.lang.String str)
      Return the last int value within a string eg :XX123XX456X: will return 456 eg :X123 456: will return 456
      static java.lang.String getNameFromState​(int state, int[] states, java.lang.String[] names)
      Starting with two arrays, one of names and one of corresponding numeric state values, find the name string that matches a given state value.
      static java.lang.String[] getNamesFromStateMasked​(int state, int[] states, int[] masks, java.lang.String[] names)
      Starting with three arrays, one of names, one of corresponding numeric state values, and one of masks for the state values, find the name string(s) that match a given state value
      static int getStateFromName​(java.lang.String name, int[] states, java.lang.String[] names)
      Starting with two arrays, one of names and one of corresponding numeric state values, find the state value that matches a given name string
      static java.lang.String hexStringFromBytes​(byte[] bytes)
      Create a String containing hexadecimal values from a byte[].
      static java.lang.String hexStringFromInts​(int[] v)
      Convert an array of integers into a single spaced hex. string.
      static java.lang.String incrementLastNumberInString​(java.lang.String str, int increment)
      Increment the last number found in a string.
      static int[] intBytesWithTotalFromNonSpacedHexString​(java.lang.String s, boolean headerTotal)
      Create an int[] from a String containing paired hexadecimal values.
      static void numberSort​(java.lang.String[] values)
      Sort String[] representing numbers, in ascending order.
      static java.lang.String padString​(java.lang.String value, int length)
      Trim a text string to length provided and (if shorter) pad with trailing spaces.
      static java.lang.String parenQuote​(java.lang.String in)
      Quotes unmatched closed parentheses; matched ( ) pairs are left unchanged.
      (package private) static java.lang.String parenUnQuote​(java.lang.String in)
      Undo parenQuote
      static java.lang.String replaceLast​(java.lang.String string, java.lang.String from, java.lang.String to)
      Replace the last occurance of string value within a String eg from ABC to DEF will convert XXABCXXXABCX to XXABCXXXDEFX
      static void sortUpperCase​(java.lang.Object[] values)
      This is a case-independent lexagraphic sort.
      static java.util.List<java.lang.String> splitParens​(java.lang.String in)  
      static java.lang.String stripHtmlTags​(java.lang.String originalText)
      Removes HTML tags from a String.
      static java.lang.String to8Bits​(int val, boolean msbLeft)
      Convert a small number to eight 1/0 characters.
      static java.lang.String twoHexFromInt​(int val)
      Convert an integer to an exactly two hexadecimal characters string
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • getStateFromName

        @CheckReturnValue
        public static int getStateFromName​(java.lang.String name,
                                           int[] states,
                                           java.lang.String[] names)
        Starting with two arrays, one of names and one of corresponding numeric state values, find the state value that matches a given name string
        Parameters:
        name - the name to search for
        states - the state values
        names - the name values
        Returns:
        the state or -1 if none found
      • getNamesFromStateMasked

        @CheckReturnValue
        public static java.lang.String[] getNamesFromStateMasked​(int state,
                                                                 int[] states,
                                                                 int[] masks,
                                                                 java.lang.String[] names)
        Starting with three arrays, one of names, one of corresponding numeric state values, and one of masks for the state values, find the name string(s) that match a given state value
        Parameters:
        state - the given state
        states - the state values
        masks - the state masks
        names - the state names
        Returns:
        names matching the given state or an empty array
      • getNameFromState

        @CheckReturnValue
        @CheckForNull
        public static java.lang.String getNameFromState​(int state,
                                                        @Nonnull
                                                        int[] states,
                                                        @Nonnull
                                                        java.lang.String[] names)
        Starting with two arrays, one of names and one of corresponding numeric state values, find the name string that matches a given state value. Only one may be returned.
        Parameters:
        state - the given state
        states - the state values
        names - the state names
        Returns:
        the first matching name or null if none found
      • twoHexFromInt

        @CheckReturnValue
        @Nonnull
        public static java.lang.String twoHexFromInt​(int val)
        Convert an integer to an exactly two hexadecimal characters string
        Parameters:
        val - the integer value
        Returns:
        String exactly two characters long
      • appendTwoHexFromInt

        @CheckReturnValue
        @Nonnull
        public static java.lang.String appendTwoHexFromInt​(int val,
                                                           @Nonnull
                                                           java.lang.String inString)
        Quickly append an integer to a String as exactly two hexadecimal characters
        Parameters:
        val - Value to append in hex
        inString - String to be extended
        Returns:
        String exactly two characters long
      • to8Bits

        @CheckReturnValue
        @Nonnull
        public static java.lang.String to8Bits​(int val,
                                               boolean msbLeft)
        Convert a small number to eight 1/0 characters.
        Parameters:
        val - the number to convert
        msbLeft - true if the MSB is on the left of the display
        Returns:
        a string of binary characters
      • hexStringFromBytes

        @CheckReturnValue
        @Nonnull
        public static java.lang.String hexStringFromBytes​(@Nonnull
                                                          byte[] bytes)
        Create a String containing hexadecimal values from a byte[]. eg. byte[]{1,2,3,10} will return String "01 02 03 0A " eg. byte[]{-1} will return "FF " eg. byte[]{(byte)256} will return "00 " eg. byte[]{(byte)257} will return "01 "
        Parameters:
        bytes - byte array. Can be zero length, but must not be null.
        Returns:
        String of hex values, ala "01 02 0A B1 21 ".
      • hexStringFromInts

        @CheckReturnValue
        @Nonnull
        public static java.lang.String hexStringFromInts​(@Nonnull
                                                         int[] v)
        Convert an array of integers into a single spaced hex. string. Each int value will receive 2 hex characters.

        eg. int[]{1,2,3,10} will return "01 02 03 0A " eg. int[]{-1} will return "FF " eg. int[]{256} will return "00 " eg. int[]{257} will return "01 "

        Parameters:
        v - the array of integers. Can be zero length, but must not be null.
        Returns:
        the formatted String or an empty String
      • bytesFromHexString

        @CheckReturnValue
        @Nonnull
        public static byte[] bytesFromHexString​(@Nonnull
                                                java.lang.String s)
        Create a byte[] from a String containing hexadecimal values.
        Parameters:
        s - String of hex values, ala "01 02 0A B1 21".
        Returns:
        byte array, with one byte for each pair. Can be zero length, but will not be null.
      • intBytesWithTotalFromNonSpacedHexString

        @Nonnull
        public static int[] intBytesWithTotalFromNonSpacedHexString​(@Nonnull
                                                                    java.lang.String s,
                                                                    boolean headerTotal)
        Create an int[] from a String containing paired hexadecimal values.

        Option to include array length as leading array value

        eg. #("01020AB121",true) returns int[5, 1, 2, 10, 177, 33]

        eg. ("01020AB121",false) returns int[1, 2, 10, 177, 33]

        Parameters:
        s - String of hex value pairs, eg "01020AB121".
        headerTotal - if true, adds index [0] with total of pairs found
        Returns:
        int array, with one field for each pair.
      • getHexDigit

        public static int getHexDigit​(int index,
                                      @Nonnull
                                      java.lang.String byteString)
        Get a single hex digit from a String.

        eg. getHexDigit(0,"ABCDEF") returns 10 eg. getHexDigit(3,"ABCDEF") returns 14

        Parameters:
        index - digit offset, 0 is very first digit on left.
        byteString - String of hex values, eg "01020AB121".
        Returns:
        hex value of single digit
      • getByte

        public static int getByte​(int b,
                                  @Nonnull
                                  java.lang.String byteString)
        Get a single hex data byte from a string

        eg. getByte(2,"0102030405") returns 3

        Parameters:
        b - The byte offset, 0 is byte 1
        byteString - the whole string, eg "01AB2CD9"
        Returns:
        The value, else 0
      • fullTextToHexArray

        @CheckReturnValue
        @Nonnull
        public static byte[] fullTextToHexArray​(@Nonnull
                                                java.lang.String s,
                                                int numBytes)
        Create a hex byte[] of Unicode character values from a String containing full text (non hex) values.

        eg fullTextToHexArray("My FroG",8) would return byte[0x4d,0x79,0x20,0x46,0x72,0x6f,0x47,0x20]

        Parameters:
        s - String, eg "Test", value is trimmed to max byte length
        numBytes - Number of bytes expected in return ( eg. to match max. message size )
        Returns:
        hex byte array, with one byte for each character. Right padded with empty spaces (0x20)
      • sortUpperCase

        public static void sortUpperCase​(@Nonnull
                                         java.lang.Object[] values)
        This is a case-independent lexagraphic sort. Identical entries are retained, so the output length is the same as the input length.
        Parameters:
        values - the Objects to sort
      • numberSort

        public static void numberSort​(@Nonnull
                                      java.lang.String[] values)
                               throws java.lang.NumberFormatException
        Sort String[] representing numbers, in ascending order.
        Parameters:
        values - the Strings to sort
        Throws:
        java.lang.NumberFormatException - if string[] doesn't only contain numbers
      • parenQuote

        @CheckReturnValue
        @CheckForNull
        public static java.lang.String parenQuote​(@CheckForNull
                                                  java.lang.String in)
        Quotes unmatched closed parentheses; matched ( ) pairs are left unchanged. If there's an unmatched ), quote it with \, and quote \ with \ too.
        Parameters:
        in - String potentially containing unmatched closing parenthesis
        Returns:
        null if given null
      • arrayToString

        @CheckReturnValue
        @Nonnull
        public static <E> java.lang.String arrayToString​(@Nonnull
                                                         E[] v)
        Convert an array of objects into a single string. Each object's toString value is displayed within square brackets and separated by commas.
        Type Parameters:
        E - the array class
        Parameters:
        v - the array to process
        Returns:
        a string; empty if the array was empty
      • arrayToString

        @CheckReturnValue
        @Nonnull
        public static java.lang.String arrayToString​(@Nonnull
                                                     byte[] v)
        Convert an array of bytes into a single string. Each element is displayed within square brackets and separated by commas.
        Parameters:
        v - the array of bytes
        Returns:
        the formatted String, or an empty String
      • arrayToString

        @CheckReturnValue
        @Nonnull
        public static java.lang.String arrayToString​(@Nonnull
                                                     int[] v)
        Convert an array of integers into a single string. Each element is displayed within square brackets and separated by commas.
        Parameters:
        v - the array of integers
        Returns:
        the formatted String or an empty String
      • padString

        @CheckReturnValue
        public static java.lang.String padString​(java.lang.String value,
                                                 int length)
        Trim a text string to length provided and (if shorter) pad with trailing spaces. Removes 1 extra character to the right for clear column view.
        Parameters:
        value - contents to process
        length - trimming length
        Returns:
        trimmed string, left aligned by padding to the right
      • getFirstIntFromString

        @CheckReturnValue
        public static int getFirstIntFromString​(@Nonnull
                                                java.lang.String str)
        Return the first int value within a string eg :X X123XX456X: will return 123 eg :X123 456: will return 123
        Parameters:
        str - contents to process
        Returns:
        first value in int form , -1 if not found
      • getLastIntFromString

        @CheckReturnValue
        public static int getLastIntFromString​(@Nonnull
                                               java.lang.String str)
        Return the last int value within a string eg :XX123XX456X: will return 456 eg :X123 456: will return 456
        Parameters:
        str - contents to process
        Returns:
        last value in int form , -1 if not found
      • incrementLastNumberInString

        @CheckForNull
        public static java.lang.String incrementLastNumberInString​(@Nonnull
                                                                   java.lang.String str,
                                                                   int increment)
        Increment the last number found in a string.
        Parameters:
        str - Initial string to increment.
        increment - number to increment by.
        Returns:
        null if not possible, else incremented String.
      • replaceLast

        @CheckReturnValue
        @Nonnull
        public static java.lang.String replaceLast​(@Nonnull
                                                   java.lang.String string,
                                                   @Nonnull
                                                   java.lang.String from,
                                                   @Nonnull
                                                   java.lang.String to)
        Replace the last occurance of string value within a String eg from ABC to DEF will convert XXABCXXXABCX to XXABCXXXDEFX
        Parameters:
        string - contents to process
        from - value within string to be replaced
        to - new value
        Returns:
        string with the replacement, original value if no match.
      • concatTextHtmlAware

        public static java.lang.String concatTextHtmlAware​(java.lang.String baseText,
                                                           java.lang.String extraText)
        Concatenates text Strings where either could possibly be in HTML format (as used in many Swing components).

        Ensures any appended text is added within the <html>...</html> element, if there is any.

        Parameters:
        baseText - original text
        extraText - text to be appended to original text
        Returns:
        Combined text, with a single enclosing <html>...</html> element (only if needed).
      • stripHtmlTags

        public static java.lang.String stripHtmlTags​(java.lang.String originalText)
        Removes HTML tags from a String. Replaces HTML line breaks with newline characters from a given input string.
        Parameters:
        originalText - The input string that may contain HTML tags.
        Returns:
        A cleaned string with HTML tags removed.