edu.northwestern.at.utils
Class StringUtils

java.lang.Object
  extended by edu.northwestern.at.utils.StringUtils

public class StringUtils
extends java.lang.Object

String utilities.

This static class provides various utility methods for manipulating strings.


Constructor Summary
protected StringUtils()
          Don't allow instantiation, do allow overrides.
 
Method Summary
static java.lang.String areOrAreNot(boolean bool)
          Return "are", "are not" based upon boolean value.
static int balPos(java.lang.StringBuffer s, int start, char lChar, char rChar)
          Find end position of balanced string.
static boolean checkEmpty(java.lang.String s)
          Checks if a string is null or empty.
static int compare(java.util.Date d1, java.util.Date d2)
          Compares two dates.
static int compare(int n1, int n2)
          Compares two ints.
static int compare(long n1, long n2)
          Compares two longs.
static int compare(java.lang.String s1, java.lang.String s2)
          Compares two case-sensitive strings.
static int compareIgnoreCase(java.lang.String s1, java.lang.String s2)
          Compares two case-insensitive strings.
static java.lang.String compressMultipleOccurrences(java.lang.String s, char c)
          Compress multiple instances of a character in a string.
static boolean containsIgnoreCaseWholeWord(java.lang.String str1, java.lang.String str2)
          Returns true if a string contains another case-insensitive string as a whole word.
static int countChar(java.lang.StringBuffer sb, char ch)
          Count occurrences of character in string buffer.
static int countOccurrences(java.lang.String source, java.lang.String searchString)
          Count occurrences of string in another string.
static java.lang.String deleteChar(java.lang.String str, char ch)
          Delete all occurrences of a specified character from a string.
static java.lang.String deleteParenthesizedText(java.lang.String s)
          Deletes parenthesized text from a string.
static java.lang.String deleteUnparenthesizedText(java.lang.String s)
          Deletes unparenthesized text from a string.
static java.lang.String displayBooleanField(java.lang.String name, boolean value)
          Displays a boolean field.
static java.lang.String displayDoubleField(java.lang.String name, double value)
          Displays a double field.
static java.lang.String displayIntegerField(java.lang.String name, int value)
          Displays an integer field.
static java.lang.String displayStringField(java.lang.String name, java.lang.String value)
          Displays a string field.
static java.lang.String dupl(char ch, int n)
          Duplicate character into string.
static java.lang.String dupl(java.lang.String s, int n)
          Duplicate string into string.
static boolean equals(java.lang.String s1, java.lang.String s2)
          Returns true if two case-sensitive strings are equal.
static boolean equalsIgnoreCase(java.lang.String s1, java.lang.String s2)
          Returns true if two case-insensitive strings are equal.
static java.lang.String escapeSpecialCharacters(java.lang.String s)
          Escape special characters.
static int extractNumber(java.lang.String str, int pos)
          Extracts a number from a string.
static java.lang.String firstLine(java.lang.String str)
          Returns the first line of a string.
static java.lang.String formatNumberWithCommas(int n)
          Formats a number with commas.
static java.lang.String formatNumberWithCommas(long n)
          Formats a number with commas.
static java.lang.String getFirstTokenFromBytes(byte[] bytes, int nBytes)
          Gets the first token from an array of bytes.
static java.lang.String haveOrHaveNot(boolean bool)
          Return "have", "have not" based upon boolean value.
static int indexOfIgnoreCaseWholeWord(java.lang.String str1, java.lang.String str2, int fromIndex)
          Searches a string for a case-insensitive whole word substring match.
static java.lang.String intersperseTextLines(java.lang.String s1, java.lang.String s2, java.lang.String s1Prefix, java.lang.String s1Suffix, java.lang.String s2Prefix, java.lang.String s2Suffix)
          Intersperse text lines from two files.
static java.lang.String intToString(int intValue)
          Convert integer to string.
static java.lang.String intToStringWithZeroFill(int intValue, int width)
          Convert integer to string with left zero fill.
static java.lang.String isOrIsNot(boolean bool)
          Return "is", "is not" based upon boolean value.
static boolean isRegularExpression(java.lang.String s)
          See if string is a regular expression.
static java.lang.String longToString(long longValue)
          Convert long to string.
static java.lang.String longToStringWithZeroFill(long longValue, int width)
          Convert long to string with left zero fill.
static java.lang.String lpad(java.lang.String s, int width)
          Left pad string with blanks to specified width.
static java.lang.String[] makeTokenArray(java.lang.String source)
          Break up a string into an array of string tokens.
static java.lang.String[] makeTokenArray(java.lang.String source, java.lang.String delim)
          Break up a string into an array of string tokens.
static java.lang.String objectToString(java.lang.Object object)
          Convert object to string representation.
static int parseNumberWithCommas(java.lang.String str)
          Parses a number with commas.
static java.lang.String pluralize(int count, java.lang.String singular, java.lang.String plural)
          Select singular or plural string based upon count.
static java.lang.String removeEnclosingBrackets(java.lang.String str)
          Remove enclosing brackets from a string.
static java.lang.String replaceAll(java.lang.String str, java.lang.String s, java.lang.String r)
          Replaces all substrings of a string.
static java.lang.String rpad(java.lang.String s, int width)
          Right pad string with blanks to specified width.
static java.lang.String safeString(java.lang.String s)
          Makes possibly null string safe for comparisons.
static java.lang.String stringToHexString(java.lang.String s)
          Convert characters in a string to hex format.
static int stringToInt(java.lang.String strValue)
          Convert string to integer.
static int stringToInt(java.lang.String strValue, int defaultValue)
          Convert string to integer.
static long stringToLong(java.lang.String strValue)
          Convert string to long.
static long stringToLong(java.lang.String strValue, long defValue)
          Convert string to long.
static java.lang.String trim(java.lang.String s)
          Trims a string.
static java.lang.String truncate(java.lang.String str, int n)
          Truncates a string and appends an ellipsis.
static java.lang.String upperCaseFirstChar(java.lang.String str)
          Converts the first character of a string to upper case.
static java.lang.String wrapLine(java.lang.String line, java.lang.String newline, int wrapColumn)
          Wrap one line of text.
static java.lang.String wrapText(java.lang.String inString, java.lang.String newline, int wrapColumn)
          Lines wraps a block of text.
static java.lang.String yesNo(boolean yesno)
          Returns "yes" or "no" for boolean value.
static java.lang.String zeroPad(java.lang.String s, int length)
          Pad string with leading zeros.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

StringUtils

protected StringUtils()
Don't allow instantiation, do allow overrides.

Method Detail

balPos

public static int balPos(java.lang.StringBuffer s,
                         int start,
                         char lChar,
                         char rChar)
Find end position of balanced string.

Parameters:
s - The string.
start - Starting offset in string.
lChar - Left delimiter.
rChar - Right delimiter to match left delimiter.
Returns:
The ending offset of the matching balanced string. -1 if not found.

countChar

public static int countChar(java.lang.StringBuffer sb,
                            char ch)
Count occurrences of character in string buffer.

Parameters:
sb - The string buffer.
ch - The character.
Returns:
Number of occurrences of ch in sb.

countOccurrences

public static int countOccurrences(java.lang.String source,
                                   java.lang.String searchString)
Count occurrences of string in another string.

Parameters:
source - The source string.
searchString - The string for which to search.
Returns:
Number of occurrences of searchString in source.

deleteChar

public static java.lang.String deleteChar(java.lang.String str,
                                          char ch)
Delete all occurrences of a specified character from a string.

Parameters:
str - The string.
ch - The character to delete.
Returns:
The string with any occurrences of "ch" removed.

displayBooleanField

public static java.lang.String displayBooleanField(java.lang.String name,
                                                   boolean value)
Displays a boolean field.

Parameters:
name - The field name.
value - The field value.
Returns:
"name = true" or "name = false".

displayIntegerField

public static java.lang.String displayIntegerField(java.lang.String name,
                                                   int value)
Displays an integer field.

Parameters:
name - The field name.
value - The field value.
Returns:
"name = value".

displayDoubleField

public static java.lang.String displayDoubleField(java.lang.String name,
                                                  double value)
Displays a double field.

Parameters:
name - The field name.
value - The field value.
Returns:
"name = value".

displayStringField

public static java.lang.String displayStringField(java.lang.String name,
                                                  java.lang.String value)
Displays a string field.

Parameters:
name - The field name.
value - The field value.
Returns:
"name = value". If the value has multiple lines the extra lines are displayed indented so that they line up with the fist line.

dupl

public static java.lang.String dupl(char ch,
                                    int n)
Duplicate character into string.

Parameters:
ch - The character to be duplicated.
n - The number of duplicates desired.
Returns:
String containing "n" copies of "ch".

if n <= 0, the empty string "" is returned.


dupl

public static java.lang.String dupl(java.lang.String s,
                                    int n)
Duplicate string into string.

Parameters:
s - The string to be duplicated.
n - The number of duplicates desired.
Returns:
String containing "n" copies of "s".

if n <= 0, the empty string "" is returned.


equals

public static boolean equals(java.lang.String s1,
                             java.lang.String s2)
Returns true if two case-sensitive strings are equal.

Nulls are permitted and are equal only to themselves.

Parameters:
s1 - String 1.
s2 - String 2.
Returns:
True if string 1 = string 2.

equalsIgnoreCase

public static boolean equalsIgnoreCase(java.lang.String s1,
                                       java.lang.String s2)
Returns true if two case-insensitive strings are equal.

Nulls are permitted and are equal only to themselves.

Parameters:
s1 - String 1.
s2 - String 2.
Returns:
True if string 1 = string 2.

compare

public static int compare(java.lang.String s1,
                          java.lang.String s2)
Compares two case-sensitive strings.

Nulls are permitted and are less than non-nulls.

Parameters:
s1 - String 1.
s2 - String 2.
Returns:
< 0 if string 1 < string 2, 0 if string 1 = string 2, > 0 if string 1 > string 2.

compareIgnoreCase

public static int compareIgnoreCase(java.lang.String s1,
                                    java.lang.String s2)
Compares two case-insensitive strings.

Nulls are permitted and are less than non-nulls.

Parameters:
s1 - String 1.
s2 - String 2.
Returns:
< 0 if string 1 < string 2, 0 if string 1 = string 2, > 0 if string 1 > string 2.

compare

public static int compare(java.util.Date d1,
                          java.util.Date d2)
Compares two dates.

Nulls are permitted and are less than non-nulls.

Parameters:
d1 - Date 1.
d2 - Date 2.
Returns:
< 0 if date 1 < date 2, 0 if date 1 = date 2, > 0 if date 1 > date 2.

compare

public static int compare(int n1,
                          int n2)
Compares two ints.

Parameters:
n1 - Int 1.
n2 - Int 2.
Returns:
-1 if n1 < n2, 0 if n1 = n2, +1 if n1 > n2.

compare

public static int compare(long n1,
                          long n2)
Compares two longs.

Parameters:
n1 - Long 1.
n2 - Long 2.
Returns:
-1 if n1 < n2, 0 if n1 = n2, +1 if n1 > n2.

indexOfIgnoreCaseWholeWord

public static int indexOfIgnoreCaseWholeWord(java.lang.String str1,
                                             java.lang.String str2,
                                             int fromIndex)
Searches a string for a case-insensitive whole word substring match.

Parameters:
str1 - The string to be searched.
str2 - The substring to search for, converted to lower case.
fromIndex - The index to start the search from.
Returns:
The index of the match, or -1 if none.

containsIgnoreCaseWholeWord

public static boolean containsIgnoreCaseWholeWord(java.lang.String str1,
                                                  java.lang.String str2)
Returns true if a string contains another case-insensitive string as a whole word.

Parameters:
str1 - The string to be searched.
str2 - The substring to search for.
Returns:
True if str1 contains str2 as a case-insensitive whole word.

extractNumber

public static int extractNumber(java.lang.String str,
                                int pos)
                         throws java.text.ParseException
Extracts a number from a string.

Parameters:
str - The string.
pos - The position within the string.
Returns:
The number.
Throws:
java.text.ParseException - If invalid number.

getFirstTokenFromBytes

public static java.lang.String getFirstTokenFromBytes(byte[] bytes,
                                                      int nBytes)
Gets the first token from an array of bytes.

Parameters:
bytes - The bytes.
nBytes - The number of bytes to scan.
Returns:
The first token as a string.

The first token is defined to end at a space, a tab, a carriage return, or a linefeed.


firstLine

public static java.lang.String firstLine(java.lang.String str)
Returns the first line of a string.

Parameters:
str - The string.
Returns:
Null if str is null, else the first line of str.

formatNumberWithCommas

public static java.lang.String formatNumberWithCommas(int n)
Formats a number with commas.

Parameters:
n - The number (int).
Returns:
The formatted number with commas.

formatNumberWithCommas

public static java.lang.String formatNumberWithCommas(long n)
Formats a number with commas.

Parameters:
n - The number (long).
Returns:
The formatted number with commas.

parseNumberWithCommas

public static int parseNumberWithCommas(java.lang.String str)
                                 throws java.text.ParseException
Parses a number with commas.

Parameters:
str - The string.
Returns:
The parsed number.
Throws:
java.text.ParseException - Invalid number.

safeString

public static java.lang.String safeString(java.lang.String s)
Makes possibly null string safe for comparisons.

Parameters:
s - Input string which may be null.
Returns:
The input string if not null, other an empty string.

replaceAll

public static java.lang.String replaceAll(java.lang.String str,
                                          java.lang.String s,
                                          java.lang.String r)
Replaces all substrings of a string.

Note: Not needed in Java 1.4 - can use replaceAll method of String class instead.

Parameters:
str - The string.
s - Substring to be replaced.
r - Replacement string.
Returns:
The string with all substrings replaced.

checkEmpty

public static boolean checkEmpty(java.lang.String s)
Checks if a string is null or empty.

Parameters:
s - String to be checked.
Returns:
True if string is null or empty.

yesNo

public static java.lang.String yesNo(boolean yesno)
Returns "yes" or "no" for boolean value.

Parameters:
yesno - Boolean value to be checked.
Returns:
"yes" if yesno is true, else "no"

areOrAreNot

public static java.lang.String areOrAreNot(boolean bool)
Return "are", "are not" based upon boolean value.

Parameters:
bool - Boolean value.
Returns:
"are" if bool is true, "are not" if false.

isOrIsNot

public static java.lang.String isOrIsNot(boolean bool)
Return "is", "is not" based upon boolean value.

Parameters:
bool - Boolean value.
Returns:
"is" if bool is true, "is not" if false.

haveOrHaveNot

public static java.lang.String haveOrHaveNot(boolean bool)
Return "have", "have not" based upon boolean value.

Parameters:
bool - Boolean value.
Returns:
"have" if bool is true, "have not" if false.

stringToInt

public static int stringToInt(java.lang.String strValue,
                              int defaultValue)
Convert string to integer.

Parameters:
strValue - The string to convert.
defaultValue - Default value if conversion error occurs.
Returns:
The string converted to an integer.

stringToHexString

public static java.lang.String stringToHexString(java.lang.String s)
Convert characters in a string to hex format.

Parameters:
s - The string to convert to hex.
Returns:
The hex version of the string.

makeTokenArray

public static java.lang.String[] makeTokenArray(java.lang.String source,
                                                java.lang.String delim)
Break up a string into an array of string tokens.

Parameters:
source - The source string.
delim - The delimiter.
Returns:
The array of tokens extracted from the source.

makeTokenArray

public static java.lang.String[] makeTokenArray(java.lang.String source)
Break up a string into an array of string tokens.

Parameters:
source - The source string.
Returns:
The array of tokens extracted from the source.

objectToString

public static java.lang.String objectToString(java.lang.Object object)
Convert object to string representation.

Parameters:
object - The object to be converted to a string representation.
Returns:
The string representation. This looks like [a, b, c ... ] for an array. If the object is not an array, its toString() method is used instead. Null objects are returned as "".

The regular java toString() routine for arrays is brain-dead: it returns the hashcode/address of the array rather than a useful representation of the array contents.


pluralize

public static java.lang.String pluralize(int count,
                                         java.lang.String singular,
                                         java.lang.String plural)
Select singular or plural string based upon count.

Parameters:
count - The number of items.
singular - The output string iif count==1 .
plural - The output string iif count!=1 .
Returns:
Either singular or plural, based upon value of count.

intToString

public static java.lang.String intToString(int intValue)
Convert integer to string.

Parameters:
intValue - The integer to convert.
Returns:
The integer converted to a string.

intToStringWithZeroFill

public static java.lang.String intToStringWithZeroFill(int intValue,
                                                       int width)
Convert integer to string with left zero fill.

Parameters:
intValue - The integer to convert.
width - Width of result field.
Returns:
The integer converted to a string with enough leading zeros to fill the specified field width.

longToString

public static java.lang.String longToString(long longValue)
Convert long to string.

Parameters:
longValue - The long to convert.
Returns:
The long converted to a string.

longToStringWithZeroFill

public static java.lang.String longToStringWithZeroFill(long longValue,
                                                        int width)
Convert long to string with left zero fill.

Parameters:
longValue - The long to convert.
width - Width of result field.
Returns:
The long converted to a string with enough leading zeros to fill the specified field width.

lpad

public static java.lang.String lpad(java.lang.String s,
                                    int width)
Left pad string with blanks to specified width.

Parameters:
s - The string to pad.
width - The width to pad to.
Returns:
"s" padded with enough blanks on left to be "width" columns wide.

rpad

public static java.lang.String rpad(java.lang.String s,
                                    int width)
Right pad string with blanks to specified width.

Parameters:
s - The string to pad.
width - The width to pad to.
Returns:
"s" padded with enough blanks on right to be "width" columns wide.

stringToInt

public static int stringToInt(java.lang.String strValue)
                       throws java.lang.NumberFormatException
Convert string to integer.

Parameters:
strValue - The string to convert.
Returns:
The string converted to an integer.
Throws:
java.lang.NumberFormatException

stringToLong

public static long stringToLong(java.lang.String strValue)
                         throws java.lang.NumberFormatException
Convert string to long.

Parameters:
strValue - The string to convert.
Returns:
The string converted to a long.
Throws:
java.lang.NumberFormatException

stringToLong

public static long stringToLong(java.lang.String strValue,
                                long defValue)
Convert string to long.

Parameters:
strValue - The string to convert.
defValue - Default value to return if string cannot be converted.
Returns:
The string converted to a long.

wrapLine

public static java.lang.String wrapLine(java.lang.String line,
                                        java.lang.String newline,
                                        int wrapColumn)
Wrap one line of text.

Parameters:
line - A line which is in need of word-wrapping.
newline - The characters that define a newline.
wrapColumn - The column to wrap the words at.
Returns:
A line with newlines inserted.

wrapText

public static java.lang.String wrapText(java.lang.String inString,
                                        java.lang.String newline,
                                        int wrapColumn)
Lines wraps a block of text.

Parameters:
inString - Text which is in need of word-wrapping.
newline - The characters that define a newline.
wrapColumn - The column to wrap the words at.
Returns:
The text with all the long lines word-wrapped.

This method wraps long lines based on the supplied wrapColumn parameter. Note: Remove or expand tabs before calling this method.


trim

public static java.lang.String trim(java.lang.String s)
Trims a string.

Parameters:
s - The string.
Returns:
The trimmed string. Leading and trailing white space characters are removed. If s is null, null is returned.

zeroPad

public static java.lang.String zeroPad(java.lang.String s,
                                       int length)
Pad string with leading zeros.

Parameters:
s - String to pad.
length - Length to pad to.
Returns:
Input string left-padded with '0' characters to specified length.

intersperseTextLines

public static java.lang.String intersperseTextLines(java.lang.String s1,
                                                    java.lang.String s2,
                                                    java.lang.String s1Prefix,
                                                    java.lang.String s1Suffix,
                                                    java.lang.String s2Prefix,
                                                    java.lang.String s2Suffix)
Intersperse text lines from two files.

Parameters:
s1 - First string containing text lines.
s2 - Second string containing text lines.
s1Prefix - Prefix for first string lines.
s1Suffix - Suffix for first string lines.
s2Prefix - Prefix for second string lines.
s2Suffix - Suffix for second string lines.
Returns:
String with lines from s1 and s2 interspersed.

deleteParenthesizedText

public static java.lang.String deleteParenthesizedText(java.lang.String s)
Deletes parenthesized text from a string.

Parameters:
s - The string from which to remove parenthesized text.
Returns:
String with parenthesized text removed.

Example:

deleteParenthesizedText( "aaaa (bb) ccc (ddd) e" )

yields

"aaaa ccc e"


deleteUnparenthesizedText

public static java.lang.String deleteUnparenthesizedText(java.lang.String s)
Deletes unparenthesized text from a string.

Parameters:
s - The string from which to remove unparenthesized text.
Returns:
String with unparenthesized text removed. Left parentheses are also removed, and right parentheses replaced by a blank.

Example:

deleteUnparenthesizedText( "aaaa (bb) ccc (ddd) e" )

yields

"bb ddd"


compressMultipleOccurrences

public static java.lang.String compressMultipleOccurrences(java.lang.String s,
                                                           char c)
Compress multiple instances of a character in a string.

Parameters:
s - The string in which to compress multiple occurrences.
c - Character whose multiple occurences should be compressed.
Returns:
String with multiple occurrences compressed.

Example:

compressMultipleOccurrences( "a b c" )

yields

"a b c"


isRegularExpression

public static boolean isRegularExpression(java.lang.String s)
See if string is a regular expression.

Parameters:
s - The string.
Returns:
true if the string appears to be a regular expression.

A string is assumed to be a regular expression if it contains any of the followint characters:

        * + - [ ] . ^ & \ $ ? { } ? =
        

truncate

public static java.lang.String truncate(java.lang.String str,
                                        int n)
Truncates a string and appends an ellipsis.

Parameters:
str - String.
n - Number of characters to retain.
Returns:
String truncated to n characters if necessary, with an ellipsis replacing the truncated characters.

upperCaseFirstChar

public static java.lang.String upperCaseFirstChar(java.lang.String str)
Converts the first character of a string to upper case.

Parameters:
str - String.
Returns:
String with first character mapped to upper case.

removeEnclosingBrackets

public static java.lang.String removeEnclosingBrackets(java.lang.String str)
Remove enclosing brackets from a string.

Parameters:
str - String from which to remove enclosing brackets [].
Returns:
str with enclosing brackets removed.

Only one level of brackets is remove. Brackets must be paired to be removed.

Examples:

  • [s] -> s
  • [s -> [s
  • s] -> s]
  • [[s]] -> [s]

escapeSpecialCharacters

public static java.lang.String escapeSpecialCharacters(java.lang.String s)
Escape special characters.

Parameters:
s - String with possible special chracters to escape.
Returns:
Return string with special characters escaped. This allows the string to be displayed, for example. If the input string is null, so is the output string.

The following characters are replaced by their "\"-escaped versions: double quote ", single quote ', new line \n, carriage return \r, tab \t, and backslash \.