com.samskivert.util
Class StringUtil

java.lang.Object
  extended by com.samskivert.util.StringUtil

public class StringUtil
extends Object

String related utility functions.


Nested Class Summary
static interface StringUtil.CharacterValidator
          Validates a character.
static class StringUtil.Formatter
          Used to format objects in listToString(Object,StringUtil.Formatter).
 
Field Summary
protected static NumberFormat _ffmt
          Used to easily format floats with sensible defaults.
protected static IntMap<Integer> _letterToBits
          Maps the 16 most frequent letters in the English language to a number between 0 and 15.
protected static String LINE_SEPARATOR
          The line separator for this platform.
protected static String XLATE
          Used by hexlate(byte[], int) and unhexlate(java.lang.String).
 
Constructor Summary
StringUtil()
           
 
Method Summary
static boolean blank(String value)
          Deprecated. use isBlank instead.
static String capitalize(String s)
          Returns a version of the supplied string with the first letter capitalized.
static String coordsToString(int x, int y)
          Formats a pair of coordinates such that positive values are rendered with a plus prefix and negative values with a minus prefix.
static void coordsToString(StringBuilder buf, int x, int y)
          Formats a pair of coordinates such that positive values are rendered with a plus prefix and negative values with a minus prefix.
static String decode(String s)
          URL decodes the specified string using the UTF-8 character encoding.
static String deNull(String value)
           
protected static String digest(String codec, String source)
          Helper function for md5hex(java.lang.String) and sha1hex(java.lang.String).
static String encode(String s)
          URL encodes the specified string using the UTF-8 character encoding.
static String fieldsToString(Object object)
          Generates a string representation of the supplied object by calling toString(java.lang.Object) on the contents of its public fields and prefixing that by the name of the fields.
static String fieldsToString(Object object, String sep)
          Like fieldsToString(Object) except that the supplied separator string will be used between fields.
static void fieldsToString(StringBuilder buf, Object object)
          Appends to the supplied string buffer a representation of the supplied object by calling toString(java.lang.Object) on the contents of its public fields and prefixing that by the name of the fields.
static void fieldsToString(StringBuilder buf, Object object, String sep)
          Like fieldsToString(StringBuilder,Object) except that the supplied separator will be used between fields.
static String fill(char c, int count)
          Returns a string containing the specified character repeated the specified number of times.
static String format(double value)
          Formats a floating point value with useful default rules; ie. always display a digit to the left of the decimal and display only two digits to the right of the decimal (rounding as necessary).
static String format(float value)
          Formats a floating point value with useful default rules; ie. always display a digit to the left of the decimal and display only two digits to the right of the decimal (rounding as necessary).
static String hexlate(byte[] bytes)
          Generates a string from the supplied bytes that is the HEX encoded representation of those bytes.
static String hexlate(byte[] bytes, int count)
          Generates a string from the supplied bytes that is the HEX encoded representation of those bytes.
static String intervalToString(long millis)
          Used to convert a time interval to a more easily human readable string of the form: 1d 15h 4m 15s 987m.
static boolean isBlank(String value)
           
static boolean isInteger(String value)
          Returns whether the supplied string represents an integer value by attempting to parse it with Integer.parseInt(java.lang.String, int).
static String join(Object[] values)
          Joins an array of strings (or objects which will be converted to strings) into a single string separated by commas.
static String join(Object[] values, boolean escape)
          Joins an array of strings into a single string, separated by commas, and optionally escaping commas that occur in the individual string values such that a subsequent call to parseStringArray(java.lang.String) would recreate the string array properly.
static String join(Object[] values, String separator)
          Joins the supplied array of strings into a single string separated by the supplied separator.
protected static String join(Object[] values, String separator, boolean escape)
          Helper function for the various join methods.
static String joinEscaped(String[] values)
          Joins an array of strings into a single string, separated by commas, and escaping commas that occur in the individual string values such that a subsequent call to parseStringArray(java.lang.String) would recreate the string array properly.
static String listToString(Object val, StringUtil.Formatter formatter)
          Formats a collection of elements (either an array of objects, an Iterator, an Enumeration or a Collection) using the supplied formatter on each element.
static void listToString(StringBuilder buf, Object val, StringUtil.Formatter formatter)
          Formats the supplied collection into the supplied string buffer using the supplied formatter.
static String md5hex(String source)
          Returns a hex string representing the MD5 encoded source.
static String pad(String value, int width)
          Pads the supplied string to the requested string width by appending spaces to the end of the returned string.
static boolean[] parseBooleanArray(String source)
          Parses an array of booleans from its string representation.
static byte[] parseByteArray(String source)
          Parses an array of signed byte-sized integers from their string representation.
static double[] parseDoubleArray(String source)
          Parses an array of doubles from its string representation.
static float[] parseFloatArray(String source)
          Parses an array of floats from it's string representation.
static int[] parseIntArray(String source)
          Parses an array of integers from it's string representation.
static long[] parseLongArray(String source)
          Parses an array of longs from it's string representation.
static short[] parseShortArray(String source)
          Parses an array of short integers from their string representation.
static String[] parseStringArray(String source)
          Parses an array of strings from a single string.
static String[] parseStringArray(String source, boolean intern)
          Like parseStringArray(String) but can be instructed to invoke String.intern() on the strings being parsed into the array.
static String prepad(String value, int width)
          Pads the supplied string to the requested string width by prepending spaces to the end of the returned string.
static String replace(String source, String before, String after)
          Returns a new string based on source with all instances of before replaced with after.
static String safeToString(Object object)
          Attempts to generate a string representation of the object using Object.toString(), but catches any exceptions that are thrown and reports them in the returned string instead.
static String sanitize(String source, String charRegex)
          Sanitize the specified String such that each character must match against the regex specified.
static String sanitize(String source, StringUtil.CharacterValidator validator)
          Sanitize the specified String so that only valid characters are in it.
static String sha1hex(String source)
          Returns a hex string representing the SHA-1 encoded source.
static String shortClassName(Class<?> clazz)
          Returns the supplied class's name, truncated to one package prior to the actual class name.
static String shortClassName(Object object)
          Returns the class name of the supplied object, truncated to one package prior to the actual class name.
static String shortClassName(String name)
          Returns the supplied class name truncated to one package prior to the actual class name.
static String spaces(int count)
          Returns a string containing the requested number of spaces.
static String[] split(String source, String sep)
          Splits the supplied string into components based on the specified separator string.
static int stringCode(String value)
          See stringCode(String,StringBuilder).
static int stringCode(String value, StringBuilder encoded)
          Encodes (case-insensitively) a short English language string into a semi-unique integer.
static String toMatrixString(int[] values, int colCount, int fieldWidth)
          Returns an array containing the values in the supplied array converted into a table of values wrapped at the specified column count and fit into the specified field width.
static String toString(Object val)
          Converts the supplied object to a string.
static String toString(Object val, String openBox, String closeBox)
          Like the single argument toString(Object) with the additional function of specifying the characters that are used to box in list and array types.
static void toString(StringBuilder buf, Object val)
          Converts the supplied value to a string and appends it to the supplied string buffer.
static void toString(StringBuilder buf, Object val, String openBox, String closeBox)
          Converts the supplied value to a string and appends it to the supplied string buffer.
static void toString(StringBuilder buf, Object val, String openBox, String closeBox, String sep)
          Converts the supplied value to a string and appends it to the supplied string buffer.
static String toUSLowerCase(String s)
          Returns a US locale lower case string.
static String toUSUpperCase(String s)
          Returns a US locale upper case string.
static String truncate(String s, int maxLength)
          Truncate the specified String if it is longer than maxLength.
static String truncate(String s, int maxLength, String append)
          Truncate the specified String if it is longer than maxLength.
static byte[] unhexlate(String hex)
          Turn a hexlated String back into a byte array.
static String unStudlyName(String name)
          Converts a name of the form weAreSoCool to a name of the form WE_ARE_SO_COOL.
static String wordWrap(String str, int width)
          Wordwraps a string.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

_ffmt

protected static final NumberFormat _ffmt
Used to easily format floats with sensible defaults.


XLATE

protected static final String XLATE
Used by hexlate(byte[], int) and unhexlate(java.lang.String).

See Also:
Constant Field Values

_letterToBits

protected static final IntMap<Integer> _letterToBits
Maps the 16 most frequent letters in the English language to a number between 0 and 15. Used by stringCode(java.lang.String).


LINE_SEPARATOR

protected static String LINE_SEPARATOR
The line separator for this platform.

Constructor Detail

StringUtil

public StringUtil()
Method Detail

blank

@Deprecated
public static boolean blank(String value)
Deprecated. use isBlank instead.

Returns:
true if the string is null or empty, false otherwise.

isBlank

public static boolean isBlank(String value)
Returns:
true if the string is null or empty, false otherwise.

deNull

public static String deNull(String value)
Returns:
the supplied string if it is non-null, "" if it is null.

truncate

public static String truncate(String s,
                              int maxLength)
Truncate the specified String if it is longer than maxLength.


truncate

public static String truncate(String s,
                              int maxLength,
                              String append)
Truncate the specified String if it is longer than maxLength. The string will be truncated at a position such that it is maxLength chars long after the addition of the 'append' String.

Parameters:
append - a String to add to the truncated String only after truncation.

capitalize

public static String capitalize(String s)
Returns a version of the supplied string with the first letter capitalized.


toUSLowerCase

public static String toUSLowerCase(String s)
Returns a US locale lower case string. Useful when manipulating filenames and resource keys which would not have locale specific characters.


toUSUpperCase

public static String toUSUpperCase(String s)
Returns a US locale upper case string. Useful when manipulating filenames and resource keys which would not have locale specific characters.


sanitize

public static String sanitize(String source,
                              StringUtil.CharacterValidator validator)
Sanitize the specified String so that only valid characters are in it.


sanitize

public static String sanitize(String source,
                              String charRegex)
Sanitize the specified String such that each character must match against the regex specified.


replace

public static String replace(String source,
                             String before,
                             String after)
Returns a new string based on source with all instances of before replaced with after.


pad

public static String pad(String value,
                         int width)
Pads the supplied string to the requested string width by appending spaces to the end of the returned string. If the original string is wider than the requested width, it is returned unmodified.


prepad

public static String prepad(String value,
                            int width)
Pads the supplied string to the requested string width by prepending spaces to the end of the returned string. If the original string is wider than the requested width, it is returned unmodified.


spaces

public static String spaces(int count)
Returns a string containing the requested number of spaces.


fill

public static String fill(char c,
                          int count)
Returns a string containing the specified character repeated the specified number of times.


isInteger

public static boolean isInteger(String value)
Returns whether the supplied string represents an integer value by attempting to parse it with Integer.parseInt(java.lang.String, int).


format

public static String format(float value)
Formats a floating point value with useful default rules; ie. always display a digit to the left of the decimal and display only two digits to the right of the decimal (rounding as necessary).


format

public static String format(double value)
Formats a floating point value with useful default rules; ie. always display a digit to the left of the decimal and display only two digits to the right of the decimal (rounding as necessary).


toString

public static String toString(Object val)
Converts the supplied object to a string. Normally this is accomplished via the object's built in toString() method, but in the case of arrays, toString() is called on each element and the contents are listed like so:
 (value, value, value)
 
Arrays of ints, longs, floats and doubles are also handled for convenience.

Additionally, Enumeration or Iterator objects can be passed and they will be enumerated and output in a similar manner to arrays. Bear in mind that this uses up the enumeration or iterator in question.

Also note that passing null will result in the string "null" being returned.


toString

public static String toString(Object val,
                              String openBox,
                              String closeBox)
Like the single argument toString(Object) with the additional function of specifying the characters that are used to box in list and array types. For example, if "[" and "]" were supplied, an int array might be formatted like so: [1, 3, 5].


toString

public static void toString(StringBuilder buf,
                            Object val)
Converts the supplied value to a string and appends it to the supplied string buffer. See the single argument version for more information.

Parameters:
buf - the string buffer to which we will append the string.
val - the value from which to generate the string.

toString

public static void toString(StringBuilder buf,
                            Object val,
                            String openBox,
                            String closeBox)
Converts the supplied value to a string and appends it to the supplied string buffer. The specified boxing characters are used to enclose list and array types. For example, if "[" and "]" were supplied, an int array might be formatted like so: [1, 3, 5].

Parameters:
buf - the string buffer to which we will append the string.
val - the value from which to generate the string.
openBox - the opening box character.
closeBox - the closing box character.

toString

public static void toString(StringBuilder buf,
                            Object val,
                            String openBox,
                            String closeBox,
                            String sep)
Converts the supplied value to a string and appends it to the supplied string buffer. The specified boxing characters are used to enclose list and array types. For example, if "[" and "]" were supplied, an int array might be formatted like so: [1, 3, 5].

Parameters:
buf - the string buffer to which we will append the string.
val - the value from which to generate the string.
openBox - the opening box character.
closeBox - the closing box character.
sep - the separator string.

listToString

public static String listToString(Object val,
                                  StringUtil.Formatter formatter)
Formats a collection of elements (either an array of objects, an Iterator, an Enumeration or a Collection) using the supplied formatter on each element. Note that if you simply wish to format a collection of elements by calling Object.toString() on each element, you can just pass the list to the toString(Object) method which will do just that.


listToString

public static void listToString(StringBuilder buf,
                                Object val,
                                StringUtil.Formatter formatter)
Formats the supplied collection into the supplied string buffer using the supplied formatter. See listToString(Object,StringUtil.Formatter) for more details.


fieldsToString

public static String fieldsToString(Object object)
Generates a string representation of the supplied object by calling toString(java.lang.Object) on the contents of its public fields and prefixing that by the name of the fields. For example:

[itemId=25, itemName=Elvis, itemCoords=(14, 25)]


fieldsToString

public static String fieldsToString(Object object,
                                    String sep)
Like fieldsToString(Object) except that the supplied separator string will be used between fields.


fieldsToString

public static void fieldsToString(StringBuilder buf,
                                  Object object)
Appends to the supplied string buffer a representation of the supplied object by calling toString(java.lang.Object) on the contents of its public fields and prefixing that by the name of the fields. For example:

itemId=25, itemName=Elvis, itemCoords=(14, 25)

Note: unlike the version of this method that returns a string, enclosing brackets are not included in the output of this method.


fieldsToString

public static void fieldsToString(StringBuilder buf,
                                  Object object,
                                  String sep)
Like fieldsToString(StringBuilder,Object) except that the supplied separator will be used between fields.


coordsToString

public static String coordsToString(int x,
                                    int y)
Formats a pair of coordinates such that positive values are rendered with a plus prefix and negative values with a minus prefix. Examples would look like: +3+4 -5+7, etc.


coordsToString

public static void coordsToString(StringBuilder buf,
                                  int x,
                                  int y)
Formats a pair of coordinates such that positive values are rendered with a plus prefix and negative values with a minus prefix. Examples would look like: +3+4 -5+7, etc.


safeToString

public static String safeToString(Object object)
Attempts to generate a string representation of the object using Object.toString(), but catches any exceptions that are thrown and reports them in the returned string instead. Useful for situations where you can't trust the rat bastards that implemented the object you're toString()ing.


encode

public static String encode(String s)
URL encodes the specified string using the UTF-8 character encoding.


decode

public static String decode(String s)
URL decodes the specified string using the UTF-8 character encoding.


hexlate

public static String hexlate(byte[] bytes,
                             int count)
Generates a string from the supplied bytes that is the HEX encoded representation of those bytes. Returns the empty string for a null or empty byte array.

Parameters:
bytes - the bytes for which we want a string representation.
count - the number of bytes to stop at (which will be coerced into being <= the length of the array).

hexlate

public static String hexlate(byte[] bytes)
Generates a string from the supplied bytes that is the HEX encoded representation of those bytes.


unhexlate

public static byte[] unhexlate(String hex)
Turn a hexlated String back into a byte array.


md5hex

public static String md5hex(String source)
Returns a hex string representing the MD5 encoded source.

Throws:
RuntimeException - thrown if the MD5 codec was not available in this JVM.

sha1hex

public static String sha1hex(String source)
Returns a hex string representing the SHA-1 encoded source.

Throws:
RuntimeException - thrown if the SHA-1 codec was not available in this JVM.

parseByteArray

public static byte[] parseByteArray(String source)
Parses an array of signed byte-sized integers from their string representation. The array should be represented as a bare list of numbers separated by commas, for example:
25, 17, 21, 99
Any inability to parse the short array will result in the function returning null.


parseShortArray

public static short[] parseShortArray(String source)
Parses an array of short integers from their string representation. The array should be represented as a bare list of numbers separated by commas, for example:
25, 17, 21, 99
Any inability to parse the short array will result in the function returning null.


parseIntArray

public static int[] parseIntArray(String source)
Parses an array of integers from it's string representation. The array should be represented as a bare list of numbers separated by commas, for example:
25, 17, 21, 99
Any inability to parse the int array will result in the function returning null.


parseLongArray

public static long[] parseLongArray(String source)
Parses an array of longs from it's string representation. The array should be represented as a bare list of numbers separated by commas, for example:
25, 17125141422, 21, 99
Any inability to parse the long array will result in the function returning null.


parseFloatArray

public static float[] parseFloatArray(String source)
Parses an array of floats from it's string representation. The array should be represented as a bare list of numbers separated by commas, for example:
25.0, .5, 1, 0.99
Any inability to parse the array will result in the function returning null.


parseDoubleArray

public static double[] parseDoubleArray(String source)
Parses an array of doubles from its string representation. The array should be represented as a bare list of numbers separated by commas, for example:
25.0, .5, 1, 0.99
Any inability to parse the array will result in the function returning null.


parseBooleanArray

public static boolean[] parseBooleanArray(String source)
Parses an array of booleans from its string representation. The array should be represented as a bare list of numbers separated by commas, for example:
false, false, true, false


parseStringArray

public static String[] parseStringArray(String source)
Parses an array of strings from a single string. The array should be represented as a bare list of strings separated by commas, for example:
mary, had, a, little, lamb, and, an, escaped, comma,,
If a comma is desired in one of the strings, it should be escaped by putting two commas in a row. Any inability to parse the string array will result in the function returning null.


parseStringArray

public static String[] parseStringArray(String source,
                                        boolean intern)
Like parseStringArray(String) but can be instructed to invoke String.intern() on the strings being parsed into the array.


join

public static String join(Object[] values)
Joins an array of strings (or objects which will be converted to strings) into a single string separated by commas.


join

public static String join(Object[] values,
                          boolean escape)
Joins an array of strings into a single string, separated by commas, and optionally escaping commas that occur in the individual string values such that a subsequent call to parseStringArray(java.lang.String) would recreate the string array properly. Any elements in the values array that are null will be treated as an empty string.


join

public static String join(Object[] values,
                          String separator)
Joins the supplied array of strings into a single string separated by the supplied separator.


joinEscaped

public static String joinEscaped(String[] values)
Joins an array of strings into a single string, separated by commas, and escaping commas that occur in the individual string values such that a subsequent call to parseStringArray(java.lang.String) would recreate the string array properly. Any elements in the values array that are null will be treated as an empty string.


split

public static String[] split(String source,
                             String sep)
Splits the supplied string into components based on the specified separator string.


toMatrixString

public static String toMatrixString(int[] values,
                                    int colCount,
                                    int fieldWidth)
Returns an array containing the values in the supplied array converted into a table of values wrapped at the specified column count and fit into the specified field width. For example, a call like toWrappedString(values, 5, 3) might result in output like so:
  12  1  9 10  3
   1  5  7  9 11
  39 15 12 80 16
 


intervalToString

public static String intervalToString(long millis)
Used to convert a time interval to a more easily human readable string of the form: 1d 15h 4m 15s 987m.


shortClassName

public static String shortClassName(Object object)
Returns the class name of the supplied object, truncated to one package prior to the actual class name. For example, com.samskivert.util.StringUtil would be reported as util.StringUtil. If a null object is passed in, null is returned.


shortClassName

public static String shortClassName(Class<?> clazz)
Returns the supplied class's name, truncated to one package prior to the actual class name. For example, com.samskivert.util.StringUtil would be reported as util.StringUtil.


shortClassName

public static String shortClassName(String name)
Returns the supplied class name truncated to one package prior to the actual class name. For example, com.samskivert.util.StringUtil would be reported as util.StringUtil.


unStudlyName

public static String unStudlyName(String name)
Converts a name of the form weAreSoCool to a name of the form WE_ARE_SO_COOL.


stringCode

public static int stringCode(String value)
See stringCode(String,StringBuilder).


stringCode

public static int stringCode(String value,
                             StringBuilder encoded)
Encodes (case-insensitively) a short English language string into a semi-unique integer. This is done by selecting the first eight characters in the string that fall into the set of the 16 most frequently used characters in the English language and converting them to a 4 bit value and storing the result into the returned integer.

This method is useful for mapping a set of string constants to a set of unique integers (e.g. mapping an enumerated type to an integer and back without having to require that the declaration order of the enumerated type remain constant for all time). The caller must, of course, ensure that no collisions occur.

Parameters:
value - the string to be encoded.
encoded - if non-null, a string buffer into which the characters used for the encoding will be recorded.

wordWrap

public static String wordWrap(String str,
                              int width)
Wordwraps a string. Treats any whitespace character as a single character.

If you want the text to wrap for a graphical display, use a wordwrapping component such as Label instead.

Parameters:
str - String to word-wrap.
width - Maximum line length.

join

protected static String join(Object[] values,
                             String separator,
                             boolean escape)
Helper function for the various join methods.


digest

protected static String digest(String codec,
                               String source)
Helper function for md5hex(java.lang.String) and sha1hex(java.lang.String).



Copyright © 2000-2008 Michael Bayne. All Rights Reserved.