Class StringUtil
- Version:
- $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/lang/StringUtil.java#2 $ return values, null-value handling and parameter names (cosmetics).
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringThe default delimiter string, used by thetoXXXArray()methods. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic StringcamelToLisp(String pString) Converts the input string from camel-style (Java in-fix) naming convention to Lisp-style naming convention (hyphen delimitted, all lower case).static Stringcapitalize(String pString) Makes the first letter of a String uppercase.static Stringcapitalize(String pString, int pIndex) Makes the Nth letter of a String uppercase.static booleanTests if a string contains a specific character.static booleanTests if a string contains another string.static booleancontainsIgnoreCase(String pString, int pChar) Tests if a string contains a specific character, ignoring case.static booleancontainsIgnoreCase(String pContainer, String pLookFor) Tests if a string contains another string, ignoring case.static StringCuts a string between two words, before a sepcified length, if the string is longer than the maxium lenght.static StringConstructs a newStringby decoding the specified sub array of bytes using the specified charset.static StringdeepToString(Object pObject) static StringdeepToString(Object pObject, boolean pForceDeep, int pDepth) (package private) static StringensureExcludesAt(String pSource, String pSubstring, int pPosition) Ensures that a string does not include a given substring at a given position.(package private) static StringensureIncludesAt(String pSource, String pSubstring, int pPosition) Ensures that a string includes a given substring at a given position.(package private) static StringformatNumber(long pNum, int pLen) Deprecated.Use StringUtil.pad instead!static StringgetFirstElement(String pSource, String pDelimiter) Gets the first element of aStringcontaining string elements delimited by a given delimiter.static StringgetLastElement(String pSource, String pDelimiter) Gets the last element of aStringcontaining string elements delimited by a given delimiter.static StringidentityToString(Object pObject) Returns a string on the same format asObject.toString().static intindexOfIgnoreCase(String pString, int pChar) Returns the index within this string of the first occurrence of the specified character.static intindexOfIgnoreCase(String pString, int pChar, int pPos) Returns the index within this string of the first occurrence of the specified character, starting at the specified index.static intindexOfIgnoreCase(String pString, String pLookFor) Returns the index within this string of the first occurrence of the specified substring.static intindexOfIgnoreCase(String pString, String pLookFor, int pPos) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.static booleanTests if a String is null, or contains nothing but white-space.static booleanTests a string array, to see if all items are null or an empty string.private static booleanisIdentityToString(Object pObject) Tests if thetoStringmethod of the given object is inherited fromObject.static booleanTests a string, to see if it is an number (element of Z).static intlastIndexOfIgnoreCase(String pString, int pChar) Returns the index within this string of the last occurrence of the specified character.static intlastIndexOfIgnoreCase(String pString, int pChar, int pPos) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.static intlastIndexOfIgnoreCase(String pString, String pLookFor) Returns the index within this string of the rightmost occurrence of the specified substring.static intlastIndexOfIgnoreCase(String pString, String pLookFor, int pPos) Returns the index within this string of the rightmost occurrence of the specified substring.static StringlispToCamel(String pString) Converts the input string from Lisp-style naming convention (hyphen delimitted, all lower case) to camel-style (Java in-fix) naming convention.static StringlispToCamel(String pString, boolean pFirstUpperCase) Converts the input string from Lisp-style naming convention (hyphen delimitted, all lower case) to camel-style (Java in-fix) naming convention.static StringTrims the argument string for whitespace on the left side only.booleanTells whether or not the given string string matches the given regular expression.static StringString length check with simple concatenation of selected pad-string.(package private) static StringremoveSubstring(String pSource, char pBeginBoundaryChar, char pEndBoundaryChar, int pOffset) Deprecated.this method actually removes all demarcated substring..(package private) static StringremoveSubstrings(String pSource, char pBeginBoundaryChar, char pEndBoundaryChar) Removes all substrings demarcated by the given string boundaries.static StringReplaces a substring of a string with another string.replaceAll(String pString, String pRegex, String pReplacement) Replaces each substring of this string that matches the given regular expression with the given pReplacement.replaceFirst(String pString, String pRegex, String pReplacement) Replaces the first substring of the given string that matches the given regular expression with the given pReplacement.static StringreplaceIgnoreCase(String pSource, String pPattern, String pReplace) Replaces a substring of a string with another string, ignoring case.static Stringstatic StringTrims the argument string for whitespace on the right side only.String[]Splits this string around matches of the given regular expression.String[]Splits this string around matches of the given regular expression.static StringGets the first substring between the given string boundaries.static ColorParses a string to a Color.static StringtoColorString(Color pColor) Creates a HTML/CSS String representation of the given color.static StringtoCSVString(Object[] pStringArray) Converts a string array to a string of comma-separated values.static StringtoCSVString(Object[] pStringArray, String pDelimiterString) Converts a string array to a string separated by the given delimiter.static DateConverts the string to a date, using the default date format.static DateConverts the string to a date, using the given format.static DatetoDate(String pString, DateFormat pFormat) Converts the string to a date, using the given format.static double[]toDoubleArray(String pString) Converts a comma-separated String to an array of doubles.static double[]toDoubleArray(String pString, String pDelimiters) Converts a comma-separated String to an array of doubles.static int[]toIntArray(String pString) Converts a comma-separated String to an array of ints.static int[]toIntArray(String pString, String pDelimiters) Converts a comma-separated String to an array of ints.static int[]toIntArray(String pString, String pDelimiters, int pBase) Converts a comma-separated String to an array of ints.static long[]toLongArray(String pString) Converts a comma-separated String to an array of longs.static long[]toLongArray(String pString, String pDelimiters) Converts a comma-separated String to an array of longs.static StringtoLowerCase(String pString) Converts a string to lowercase.static String[]toStringArray(String pString) Converts a comma-separated String to an array of Strings.static String[]toStringArray(String pString, String pDelimiters) Converts a delimiter separated String to an array of Strings.static TimestamptoTimestamp(String pValue) Converts the string to a jdbc Timestamp, using the standard Timestamp escape format.static StringtoUpperCase(String pString) Converts a string to uppercase.static StringReturns the value of the givenObject, as aString.
-
Field Details
-
DELIMITER_STRING
The default delimiter string, used by thetoXXXArray()methods. Its value is", \t\n\r\f".- See Also:
-
-
Constructor Details
-
StringUtil
private StringUtil()
-
-
Method Details
-
decode
Constructs a newStringby decoding the specified sub array of bytes using the specified charset. Replacement fornew String(byte[], int, int, String), that does not throw the checkedUnsupportedEncodingException, but instead the uncheckedUnsupportedCharsetExceptionif the character set is not supported.- Parameters:
pData- the bytes to be decoded to characterspOffset- the index of the first byte to decodepLength- the number of bytes to decodepCharset- the name of a supported character set- Returns:
- a newly created string.
- Throws:
UnsupportedCharsetException- See Also:
-
valueOf
Returns the value of the givenObject, as aString. Unlike String.valueOf, this method returnsnullinstead of theString"null", ifnullis given as the argument.- Parameters:
pObj- the Object to find theStringvalue of.- Returns:
- the String value of the given object, or
nullif thepObj==null. - See Also:
-
toUpperCase
-
toLowerCase
-
isEmpty
Tests if a String is null, or contains nothing but white-space.- Parameters:
pString- The string to test- Returns:
- true if the string is null or contains only whitespace, otherwise false.
-
isEmpty
Tests a string array, to see if all items are null or an empty string.- Parameters:
pStringArray- The string array to check.- Returns:
- true if the string array is null or only contains string items that are null or contain only whitespace, otherwise false.
-
contains
Tests if a string contains another string.- Parameters:
pContainer- The string to testpLookFor- The string to look for- Returns:
trueif the container string is contains the string, and both parameters are non-null, otherwisefalse.
-
containsIgnoreCase
Tests if a string contains another string, ignoring case.- Parameters:
pContainer- The string to testpLookFor- The string to look for- Returns:
trueif the container string is contains the string, and both parameters are non-null, otherwisefalse.- See Also:
-
contains
Tests if a string contains a specific character.- Parameters:
pString- The string to check.pChar- The character to search for.- Returns:
- true if the string contains the specific character.
-
containsIgnoreCase
Tests if a string contains a specific character, ignoring case.- Parameters:
pString- The string to check.pChar- The character to search for.- Returns:
- true if the string contains the specific character.
-
indexOfIgnoreCase
Returns the index within this string of the first occurrence of the specified substring.- Parameters:
pString- The string to testpLookFor- The string to look for- Returns:
- if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
- See Also:
-
indexOfIgnoreCase
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.- Parameters:
pString- The string to testpLookFor- The string to look forpPos- The first index to test- Returns:
- if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
- See Also:
-
lastIndexOfIgnoreCase
Returns the index within this string of the rightmost occurrence of the specified substring. The rightmost empty string "" is considered to occur at the index valuepString.length() - 1.- Parameters:
pString- The string to testpLookFor- The string to look for- Returns:
- If the string argument occurs one or more times as a substring within this object at a starting index no greater than fromIndex, then the index of the first character of the last such substring is returned. If it does not occur as a substring starting at fromIndex or earlier, -1 is returned.
- See Also:
-
lastIndexOfIgnoreCase
Returns the index within this string of the rightmost occurrence of the specified substring. The rightmost empty string "" is considered to occur at the index valuepPos- Parameters:
pString- The string to testpLookFor- The string to look forpPos- The last index to test- Returns:
- If the string argument occurs one or more times as a substring within this object at a starting index no greater than fromIndex, then the index of the first character of the last such substring is returned. If it does not occur as a substring starting at fromIndex or earlier, -1 is returned.
- See Also:
-
indexOfIgnoreCase
Returns the index within this string of the first occurrence of the specified character.- Parameters:
pString- The string to testpChar- The character to look for- Returns:
- if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
- See Also:
-
indexOfIgnoreCase
Returns the index within this string of the first occurrence of the specified character, starting at the specified index.- Parameters:
pString- The string to testpChar- The character to look forpPos- The first index to test- Returns:
- if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
- See Also:
-
lastIndexOfIgnoreCase
Returns the index within this string of the last occurrence of the specified character.- Parameters:
pString- The string to testpChar- The character to look for- Returns:
- if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
- See Also:
-
lastIndexOfIgnoreCase
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.- Parameters:
pString- The string to testpChar- The character to look forpPos- The last index to test- Returns:
- if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
- See Also:
-
ltrim
-
rtrim
-
replace
Replaces a substring of a string with another string. All matches are replaced.- Parameters:
pSource- The source StringpPattern- The pattern to replacepReplace- The new String to be inserted instead of the replace String- Returns:
- The new String with the pattern replaced
-
replaceIgnoreCase
Replaces a substring of a string with another string, ignoring case. All matches are replaced.- Parameters:
pSource- The source StringpPattern- The pattern to replacepReplace- The new String to be inserted instead of the replace String- Returns:
- The new String with the pattern replaced
- See Also:
-
cut
Cuts a string between two words, before a sepcified length, if the string is longer than the maxium lenght. The string is optionally padded with the pad argument. The method assumes words to be separated by the space character (" "). Note that the maximum length argument is absolute, and will also include the length of the padding.- Parameters:
pString- The string to cutpMaxLen- The maximum length before cuttingpPad- The string to append at the end, aftrer cutting- Returns:
- The cutted string with padding, or the original string, if it was shorter than the max length.
- See Also:
-
capitalize
Makes the Nth letter of a String uppercase. If the index is outside the the length of the argument string, the argument is simply returned.- Parameters:
pString- The string to capitalizepIndex- The base-0 index of the char to capitalize.- Returns:
- The capitalized string, or null, if a null argument was given.
-
capitalize
-
formatNumber
Deprecated.Use StringUtil.pad instead!Formats a number with leading zeroes, to a specified length.- Parameters:
pNum- The number to formatpLen- The number of digits- Returns:
- A string containing the formatted number
- Throws:
IllegalArgumentException- Thrown, if the number contains more digits than allowed by the length argument.- See Also:
-
pad
String length check with simple concatenation of selected pad-string. E.g. a zip number from 123 to the correct 0123.- Parameters:
pSource- The source string.pRequiredLength- The accurate length of the resulting string.pPadString- The string for concatenation.pPrepend- The location of fill-ins, prepend (true), or append (false)- Returns:
- a concatenated string.
- See Also:
-
toDate
-
toDate
-
toDate
Converts the string to a date, using the given format.- Parameters:
pString- the string to convertpFormat- the date format- Returns:
- the date
- See Also:
-
toTimestamp
-
toStringArray
-
toStringArray
-
toIntArray
Converts a comma-separated String to an array of ints.- Parameters:
pString- The comma-separated stringpDelimiters- The delimiter stringpBase- The radix- Returns:
- an
intarray - Throws:
NumberFormatException- if any of the elements are not parseable as an int
-
toIntArray
Converts a comma-separated String to an array of ints.- Parameters:
pString- The comma-separated string- Returns:
- an
intarray - Throws:
NumberFormatException- if any of the elements are not parseable as an int- See Also:
-
toIntArray
Converts a comma-separated String to an array of ints.- Parameters:
pString- The comma-separated stringpDelimiters- The delimiter string- Returns:
- an
intarray - Throws:
NumberFormatException- if any of the elements are not parseable as an int- See Also:
-
toLongArray
Converts a comma-separated String to an array of longs.- Parameters:
pString- The comma-separated stringpDelimiters- The delimiter string- Returns:
- a
longarray - Throws:
NumberFormatException- if any of the elements are not parseable as a long
-
toLongArray
Converts a comma-separated String to an array of longs.- Parameters:
pString- The comma-separated string- Returns:
- a
longarray - Throws:
NumberFormatException- if any of the elements are not parseable as a long- See Also:
-
toDoubleArray
Converts a comma-separated String to an array of doubles.- Parameters:
pString- The comma-separated stringpDelimiters- The delimiter string- Returns:
- a
doublearray - Throws:
NumberFormatException- if any of the elements are not parseable as a double
-
toDoubleArray
Converts a comma-separated String to an array of doubles.- Parameters:
pString- The comma-separated string- Returns:
- a
doublearray - Throws:
NumberFormatException- if any of the elements are not parseable as a double- See Also:
-
toColor
Parses a string to a Color. The argument can be a color constant (static constant fromjava.awt.Color), likeblackorred, or it can be HTML/CSS-style, on the format:#RRGGBB, where RR, GG and BB means two digit hexadecimal for red, green and blue values respectively.#AARRGGBB, as above, with AA as alpha component.#RGB, where R, G and B means one digit hexadecimal for red, green and blue values respectively.#ARGB, as above, with A as alpha component.
- Parameters:
pString- the string representation of the color- Returns:
- the
Colorobject, ornullif the argument isnull - Throws:
IllegalArgumentException- if the string does not map to a color.- See Also:
-
toColorString
Creates a HTML/CSS String representation of the given color. The HTML/CSS color format is defined as:#RRGGBB, where RR, GG and BB means two digit hexadecimal for red, green and blue values respectively.#AARRGGBB, as above, with AA as alpha component.
Examlples:
toColorString(Color.red) == "#ff0000",toColorString(new Color(0xcc, 0xcc, 0xcc)) == "#cccccc".- Parameters:
pColor- the color- Returns:
- A String representation of the color on HTML/CSS form
-
isNumber
Tests a string, to see if it is an number (element of Z). Valid integers are positive natural numbers (1, 2, 3, ...), their negatives (?1, ?2, ?3, ...) and the number zero.Note that there is no guarantees made, that this number can be represented as either an int or a long.
- Parameters:
pString- The string to check.- Returns:
- true if the String is a natural number.
-
ensureIncludesAt
Ensures that a string includes a given substring at a given position.Extends the string with a given string if it is not already there. E.g an URL "www.vg.no", to "http://www.vg.no".
- Parameters:
pSource- The source string.pSubstring- The substring to include.pPosition- The location of the fill-in, the index starts with 0.- Returns:
- the string, with the substring at the given location.
-
ensureExcludesAt
Ensures that a string does not include a given substring at a given position.Removes a given substring from a string if it is there. E.g an URL "http://www.vg.no", to "www.vg.no".
- Parameters:
pSource- The source string.pSubstring- The substring to check and possibly remove.pPosition- The location of possible substring removal, the index starts with 0.- Returns:
- the string, without the substring at the given location.
-
substring
public static String substring(String pSource, String pBeginBoundaryString, String pEndBoundaryString, int pOffset) Gets the first substring between the given string boundaries.- Parameters:
pSource- The source string.pBeginBoundaryString- The string that marks the beginning.pEndBoundaryString- The string that marks the end.pOffset- The index to start searching in the source string. If it is less than 0, the index will be set to 0.- Returns:
- the substring demarcated by the given string boundaries or null if not both string boundaries are found.
-
removeSubstring
@Deprecated static String removeSubstring(String pSource, char pBeginBoundaryChar, char pEndBoundaryChar, int pOffset) Deprecated.this method actually removes all demarcated substring.. doesn't it?Removes the first substring demarcated by the given string boundaries.- Parameters:
pSource- The source string.pBeginBoundaryChar- The character that marks the beginning of the unwanted substring.pEndBoundaryChar- The character that marks the end of the unwanted substring.pOffset- The index to start searching in the source string. If it is less than 0, the index will be set to 0.- Returns:
- the source string with all the demarcated substrings removed, included the demarcation characters.
-
removeSubstrings
Removes all substrings demarcated by the given string boundaries.- Parameters:
pSource- The source string.pBeginBoundaryChar- The character that marks the beginning of the unwanted substring.pEndBoundaryChar- The character that marks the end of the unwanted substring.- Returns:
- the source string with all the demarcated substrings removed, included the demarcation characters.
-
getFirstElement
Gets the first element of aStringcontaining string elements delimited by a given delimiter. NB - Straightforward implementation!- Parameters:
pSource- The source string.pDelimiter- The delimiter used in the source string.- Returns:
- The last string element.
-
getLastElement
Gets the last element of aStringcontaining string elements delimited by a given delimiter. NB - Straightforward implementation!- Parameters:
pSource- The source string.pDelimiter- The delimiter used in the source string.- Returns:
- The last string element.
-
toCSVString
-
toCSVString
Converts a string array to a string separated by the given delimiter.- Parameters:
pStringArray- the string arraypDelimiterString- the delimiter string- Returns:
- string of delimiter separated values
- Throws:
IllegalArgumentException- ifpDelimiterString == null
-
deepToString
-
deepToString
-
isIdentityToString
Tests if thetoStringmethod of the given object is inherited fromObject.- Parameters:
pObject- the object- Returns:
trueif toString of class Object
-
identityToString
-
matches
Tells whether or not the given string string matches the given regular expression.An invocation of this method of the form matches(str, regex) yields exactly the same result as the expression
Pattern.matches(regex, str)- Parameters:
pString- the stringpRegex- the regular expression to which this string is to be matched- Returns:
trueif, and only if, this string matches the given regular expression- Throws:
PatternSyntaxException- if the regular expression's syntax is invalid- See Also:
-
replaceFirst
Replaces the first substring of the given string that matches the given regular expression with the given pReplacement.An invocation of this method of the form replaceFirst(str, regex, repl) yields exactly the same result as the expression:
Pattern.compile(regex).matcher(str).replaceFirst(repl)- Parameters:
pString- the stringpRegex- the regular expression to which this string is to be matchedpReplacement- the replacement text- Returns:
- The resulting
String - Throws:
PatternSyntaxException- if the regular expression's syntax is invalid- See Also:
-
replaceAll
Replaces each substring of this string that matches the given regular expression with the given pReplacement.An invocation of this method of the form replaceAll(str, pRegex, repl) yields exactly the same result as the expression
Pattern.compile(pRegex).matcher(str). {@link java.util.regex.Matcher#replaceAll replaceAll}(repl)- Parameters:
pString- the stringpRegex- the regular expression to which this string is to be matchedpReplacement- the replacement string- Returns:
- The resulting
String - Throws:
PatternSyntaxException- if the regular expression's syntax is invalid- See Also:
-
split
Splits this string around matches of the given regular expression.The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
The
pLimitparameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the pLimit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.An invocation of this method of the form split(str, regex, n) yields the same result as the expression:
Pattern.compile(regex).split(str, n)- Parameters:
pString- the stringpRegex- the delimiting regular expressionpLimit- the result threshold, as described above- Returns:
- the array of strings computed by splitting this string around matches of the given regular expression
- Throws:
PatternSyntaxException- if the regular expression's syntax is invalid- See Also:
-
split
Splits this string around matches of the given regular expression.This method works as if by invoking the two-argument
splitmethod with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.- Parameters:
pString- the stringpRegex- the delimiting regular expression- Returns:
- the array of strings computed by splitting this string around matches of the given regular expression
- Throws:
PatternSyntaxException- if the regular expression's syntax is invalid- See Also:
-
camelToLisp
Converts the input string from camel-style (Java in-fix) naming convention to Lisp-style naming convention (hyphen delimitted, all lower case). Other characters in the string are left untouched.Eg.
"foo" => "foo","fooBar" => "foo-bar","myURL" => "my-url","HttpRequestWrapper" => "http-request-wrapper""HttpURLConnection" => "http-url-connection""my45Caliber" => "my-45-caliber""allready-lisp" => "allready-lisp"- Parameters:
pString- the camel-style input string- Returns:
- the string converted to lisp-style naming convention
- Throws:
IllegalArgumentException- ifpString == null- See Also:
-
lispToCamel
Converts the input string from Lisp-style naming convention (hyphen delimitted, all lower case) to camel-style (Java in-fix) naming convention. Other characters in the string are left untouched.Eg.
"foo" => "foo","foo-bar" => "fooBar","http-request-wrapper" => "httpRequestWrapper""my-45-caliber" => "my45Caliber""allreadyCamel" => "allreadyCamel"- Parameters:
pString- the lisp-style input string- Returns:
- the string converted to camel-style
- Throws:
IllegalArgumentException- ifpString == null- See Also:
-
lispToCamel
Converts the input string from Lisp-style naming convention (hyphen delimitted, all lower case) to camel-style (Java in-fix) naming convention. Other characters in the string are left untouched.To create a string starting with a lower case letter (like Java variable names, etc), specify the
pFirstUpperCaseparamter to befalse. Eg."foo" => "foo","foo-bar" => "fooBar","allreadyCamel" => "allreadyCamel"To create a string starting with an upper case letter (like Java class name, etc), specify the
pFirstUpperCaseparamter to betrue. Eg."http-request-wrapper" => "HttpRequestWrapper""my-12-monkeys" => "My12Monkeys"- Parameters:
pString- the lisp-style input stringpFirstUpperCase-trueif the first char should be upper case- Returns:
- the string converted to camel-style
- Throws:
IllegalArgumentException- ifpString == null- See Also:
-
reverse
-