com.ccg.util
Class StringUtils

java.lang.Object
  extended by com.ccg.util.StringUtils
All Implemented Interfaces:
Comparator

public class StringUtils
extends Object
implements Comparator

Set of functions related to String objects and arrays of String objects.

Seems like there are always a set of common manipulations which are done to string objects or arrays of string objects. This class attempts to encapsulate some of these common needs into a single location.

A user of this class will need to look at each of the methods to decide what is useful for their application/purpose.

As an example of some of the power of these functions, lets assume that you have a hash table where the keys are string identifiers. The following code fragment would returns all of the keys from your hash table as a sorted array:

   public String[] getSortedKeys(Hashtable ht) {
      StringUtils su = new StringUtils();
      String[] sa = su.toArray(ht.keys());
        return su.sortDup(sa);
   }
 

NOTE: This class also acts as a Comparator for String objects and is preferable to the CompareStrings class - which I may end up deprecating in the future.

Since:
1.0
Version:
$Revision: 1.5 $
Author:
$Author: pkb $

Field Summary
static String[] EMPTY_ARRAY
          A constant (which everyone may use) that defines a zero length array of string objects.
 
Constructor Summary
StringUtils()
          Default constructor for the class.
 
Method Summary
 int compare(Object o1, Object o2)
          Compare the String representations of two objects.
 String getBlankReplace()
          Get the string value to replace blank strings (zero length) with when converting collections of strings.
 Comparator getComparator()
          Get the comparator to use when sorting strings.
 String getNullReplace()
          Get the string value to replace 'null' entries with when converting collections.
 boolean isBlankSkipped()
          Should we skip (omit) 'blank' string objects when working with collections?
 boolean isCaseIgnored()
          Is case ignored when making string comparisons?
 boolean isDescending()
          Is a descending sort to be generated set?
 boolean isNullSkipped()
          Should we skip (omit) 'null' string objects when working with collections?
static String repeat(char fill, int cnt)
          Create a string which contains a single character repeated zero or more times.
 void setBlankReplace(String val)
          Set the string value to replace blank strings (zero length) with when converting collections of strings.
 void setBlankSkipped(boolean val)
          Set whether we should we skip (omit) 'blank' string objects when working with collections.
 void setCaseIgnored(boolean val)
          Set whether case should be ignored when making string comparisons.
 void setComparator(Comparator val)
          Set the comparator to use when sorting strings.
 void setDescending(boolean val)
          Set whether a descending sort should be generated.
 void setNullReplace(String val)
          Set the string value to replace 'null' entries with when converting collections.
 void setNullSkipped(boolean val)
          Set whether we should we skip (omit) 'null' string objects when working with collections.
 void sort(String[] sa)
          Sorts an array of string objects in place (modifying array passed).
 String[] sortDup(String[] sa)
          Sorts an array of string objects, returning a new array of sorted strings.
 String[] toArray(Enumeration e)
          Convert Enumeration of objects to a array of strings.
 String[] toArray(Iterator iter)
          Converts a collection of strings to a array of strings imposing the skip and replacement rules.
static String toString(boolean val)
          Convert a boolean primitive to its string representation.
static String toString(byte val)
          Convert a byte primitive to its string representation.
static String toString(char val)
          Convert a char primitive to its string representation.
static String toString(double val)
          Convert a double primitive to its string representation.
static String toString(float val)
          Convert a float primitive to its string representation.
 String toString(InputStream in)
          Read the the contents of a InputStream into a String.
static String toString(int val)
          Convert a int primitive to its string representation.
static String toString(long val)
          Convert a long primitive to its string representation.
 String toString(Object o)
          Convert any object to its string representation (safely checking for null and blank values).
static String toString(short val)
          Convert a short primitive to its string representation.
 Vector toVector(Enumeration e)
          Convert Enumeration of objects to a Vector of Strings.
 Vector toVector(Iterator i)
          Converts a collection of strings to a Vector of strings imposing the skip and replacement rules.
 Vector toVector(String s)
          Read all lines of text from a single string and return a Vector of each line read.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface java.util.Comparator
equals
 

Field Detail

EMPTY_ARRAY

public static final String[] EMPTY_ARRAY
A constant (which everyone may use) that defines a zero length array of string objects.

This constant defines a array of strings which contains zero entries. It is non-mutable, so it is freely useable by ALL code within the JVM.

If used wisely, this does the following:

Since:
1.0
Constructor Detail

StringUtils

public StringUtils()
Default constructor for the class. When a object is constructed using this default constructor, the following rules are in affect:

Since:
1.0
Method Detail

repeat

public static String repeat(char fill,
                            int cnt)
Create a string which contains a single character repeated zero or more times.

Parameters:
fill - The character to repeat.
cnt - How many times the character should be repeated (0 or larger).
Returns:
A string which repeats 'fill' count times.
Since:
1.0

sort

public void sort(String[] sa)
Sorts an array of string objects in place (modifying array passed).

This method sorts an array of string objects in place (updating the array passed). It should be noted that if your array contains null values or empty strings, then the Comparator associated with the object must be able to handle these conditions (the default one used - if you don't specify one - is capable of this).

You may want to take a look at the sortDup(java.lang.String[]) method (which leaves your original array alone).

Parameters:
sa - Array of String objects to be sorted (you may pass null).
Since:
1.0
See Also:
sortDup(java.lang.String[])

sortDup

public String[] sortDup(String[] sa)
Sorts an array of string objects, returning a new array of sorted strings.

This method sorts an array of string objects returning a new array of sorted strings. It should be noted that if your original array contained null values or empty strings, then the returned array may omit or replace these values depending upon the 'skip' and 'replace' rules which are in affect.

Parameters:
sa - Array of String objects to be sorted (you may pass null). This method does NOT modify this arrays contents.
Returns:
New array of sorted strings. Never returns null, but may return EMPTY_ARRAY.
Since:
1.0
See Also:
sort(java.lang.String[])

toVector

public Vector toVector(Iterator i)
Converts a collection of strings to a Vector of strings imposing the skip and replacement rules.

This method goes through a iterator and constructs a Vector objecting containing JUST string representations of each entry iterated over. This imposes the 'skip' and 'replacement' rules currently in affect (null and blank values might be skipped or replaced in the process of building the resulting vector).

NOTE: The 'skip' rules are imposed PRIOR to the 'replace' rules. For example, if you set the null skipped rule to true and null replacement to "NULL" and null values encountered would be 'skipped' and NOT replaced by "NULL". The replacement value of "NULL" would never be used as the 'skip' rule was imposed first.

Parameters:
i - Iterator which we should step through to build our vector of strings (you can pass null - in which case we'll return EMPTY_ARRAY).
Returns:
Vector of strings converted from collection. Never returns null, but may return a zero length array.
Since:
1.0
See Also:
setNullSkipped(boolean), setBlankSkipped(boolean), setNullReplace(java.lang.String), setBlankReplace(java.lang.String), toArray(Iterator), EnumerationIterator

toArray

public String[] toArray(Iterator iter)
Converts a collection of strings to a array of strings imposing the skip and replacement rules.

This method goes through a iterator and constructs a string array containing string representations of each entry iterated over. This imposes the 'skip' and 'replacement' rules currently in affect (null and blank values might be skipped or replaced in the process of building the resulting vector).

NOTE: The 'skip' rules are imposed PRIOR to the 'replace' rules. For example, if you set the null skipped rule to true and null replacement to "NULL" and null values encountered would be 'skipped' and NOT replaced by "NULL". The replacement value of "NULL" would never be used as the 'skip' rule was imposed first.

Parameters:
i - Iterator which we should step through to build our array of strings (you can pass null - in which case we'll return EMPTY_ARRAY).
Returns:
Array of strings converted from collection. Never returns null, but may return EMPTY_ARRAY.
Since:
1.0
See Also:
setNullSkipped(boolean), setBlankSkipped(boolean)

toVector

public Vector toVector(Enumeration e)
Convert Enumeration of objects to a Vector of Strings.

This is a convenience method which converts the Enumeration passed into a Iterator and then invokes toVector(Iterator).

Parameters:
e - Enumeration which we should step through to build our vector of strings (you can pass null - in which case we'll return EMPTY_ARRAY).
Returns:
Array of strings converted from collection. Never returns null, but may return EMPTY_ARRAY.
Since:
1.0
See Also:
toVector(Iterator)

toVector

public Vector toVector(String s)
Read all lines of text from a single string and return a Vector of each line read.

This is a convenience method which expects to be passed a single string containing multiple lines of text. Each line of text is added to a Vector which is then returned.

Parameters:
s - String containing multiple lines of text (you can pass null or single lines of text as well).
Returns:
A vector of lines taken from the string.
Since:
1.0
See Also:
toVector(Iterator)

toArray

public String[] toArray(Enumeration e)
Convert Enumeration of objects to a array of strings.

This is a convenience method which converts the Enumeration passed into a Iterator and then invokes toArray(Iterator).

Parameters:
e - Enumeration which we should step through to build our array of strings (you can pass null - in which case we'll return EMPTY_ARRAY).
Returns:
Array of strings converted from collection. Never returns null, but may return EMPTY_ARRAY.
Since:
1.0
See Also:
toArray(Iterator)

toString

public String toString(InputStream in)
                throws IOException
Read the the contents of a InputStream into a String.

This method reads the entire contents of a InputStream and returns the contents as a String.

NOTE: The entire contents of the stream are read and processed - so this should NOT be used with large files.

Parameters:
in - InputStream to read (in its entirety) - if you pass null, you get "" back.
Returns:
Contents of input stream as a String.
Throws:
IOException - If an error occurs while reading contents from input stream.
Since:
1.0

toString

public static String toString(boolean val)
Convert a boolean primitive to its string representation.

This method converts a boolean value to its corresponding string representation in a language independent (non-localized) form. This is done in a manner such that the string value returned could be later used to initialize a Boolean object as demonstrated in the following:


 Boolean toObject(boolean val) {
   return new Boolean(StringUtils.toString(val));
 }
 

This can be handy if you want to save the state of primitives in a ASCII form that you will want to be able to restore later.

Parameters:
val - boolean value to get a string representation of.
Returns:
String representation to convert.
Since:
1.0

toString

public static String toString(byte val)
Convert a byte primitive to its string representation.

This method converts a byte value to its corresponding string representation in a language independent (non-localized) form. This is done in a manner such that the string value returned could be later used to initialize a Byte object as demonstrated in the following:


 Byte toObject(byte val) {
   return new Byte(StringUtils.toString(val));
 }
 

This can be handy if you want to save the state of primitives in a ASCII form that you will want to be able to restore later.

Parameters:
val - byte value to get a string representation of.
Returns:
String representation to convert.
Since:
1.0

toString

public static String toString(char val)
Convert a char primitive to its string representation.

This method converts a char value to its corresponding string representation in a language independent (non-localized) form.

This can be handy if you want to save the state of primitives in a ASCII form that you will want to be able to restore later.

Parameters:
val - char value to get a string representation of.
Returns:
String representation to convert.
Since:
1.0

toString

public static String toString(short val)
Convert a short primitive to its string representation.

This method converts a short value to its corresponding string representation in a language independent (non-localized) form. This is done in a manner such that the string value returned could be later used to initialize a Short object as demonstrated in the following:


 Short toObject(short val) {
   return new Short(StringUtils.toString(val));
 }
 

This can be handy if you want to save the state of primitives in a ASCII form that you will want to be able to restore later.

Parameters:
val - short value to get a string representation of.
Returns:
String representation to convert.
Since:
1.0

toString

public static String toString(int val)
Convert a int primitive to its string representation.

This method converts a int value to its corresponding string representation in a language independent (non-localized) form. This is done in a manner such that the string value returned could be later used to initialize a Integer object as demonstrated in the following:


 Integer toObject(int val) {
   return new Integer(StringUtils.toString(val));
 }
 

This can be handy if you want to save the state of primitives in a ASCII form that you will want to be able to restore later.

Parameters:
val - int value to get a string representation of.
Returns:
String representation to convert.
Since:
1.0

toString

public static String toString(long val)
Convert a long primitive to its string representation.

This method converts a long value to its corresponding string representation in a language independent (non-localized) form. This is done in a manner such that the string value returned could be later used to initialize a Long object as demonstrated in the following:


 Long toObject(long val) {
   return new Long(StringUtils.toString(val));
 }
 

This can be handy if you want to save the state of primitives in a ASCII form that you will want to be able to restore later.

Parameters:
val - long value to get a string representation of.
Returns:
String representation to convert.
Since:
1.0

toString

public static String toString(float val)
Convert a float primitive to its string representation.

This method converts a float value to its corresponding string representation in a language independent (non-localized) form. This is done in a manner such that the string value returned could be later used to initialize a Float object as demonstrated in the following:


 Float toObject(float val) {
   return new Float(StringUtils.toString(val));
 }
 

This can be handy if you want to save the state of primitives in a ASCII form that you will want to be able to restore later.

Parameters:
val - float value to get a string representation of.
Returns:
String representation to convert.
Since:
1.0

toString

public static String toString(double val)
Convert a double primitive to its string representation.

This method converts a double value to its corresponding string representation in a language independent (non-localized) form. This is done in a manner such that the string value returned could be later used to initialize a Double object as demonstrated in the following:


 Double toObject(double val) {
   return new Double(StringUtils.toString(val));
 }
 

This can be handy if you want to save the state of primitives in a ASCII form that you will want to be able to restore later.

Parameters:
val - double value to get a string representation of.
Returns:
String representation to convert.
Since:
1.0

toString

public String toString(Object o)
Convert any object to its string representation (safely checking for null and blank values).

Often one finds themselves retrieving string values of objects in one of the following manner:

        // Direct cast approach
 Object o = "Hello";
 String s0 = (String) o;
 System.println(s0);

 String s1 = o.toString();
 System.println(s1);

 

The above works well if you know that your object is not null AND that its string representation is not null AND (in the 'Direct cast' approach) is a String object. However, if any of these are violated, the above code will break.

This method, provides a "safer" way to do this type of casting. It handles the condition when you pass null, a object which is not a string or a object who's string representation is null. In addition, it allows you to remap the null and blank values of the string. For example:

 StringUtils su = new StringUtils();

                        // Prints: ":::hello"
 System.out.println(":"+su.toString(null)+":"+
                        su.toString("")+":"+su.toString("hello"));

                        // Prints: ":X:Y:hello"
 su.setNullReplace("X");
 su.setBlankReplace("Y");
 System.out.println(":"+su.toString(null)+":"+
                        su.toString("")+":"+su.toString("hello"));
 

Parameters:
o - Object which you want to get the string value for (may be null).
Returns:
The string representation of the object if it is not null and its string representation is more than zero characters in length, otherwise it returns the corresponding blank or null replacement value.
Since:
1.0

setNullReplace

public void setNullReplace(String val)
Set the string value to replace 'null' entries with when converting collections.

Parameters:
val - New String value to assign.
See Also:
getNullReplace()

getNullReplace

public String getNullReplace()
Get the string value to replace 'null' entries with when converting collections.

Returns:
Current String value assigned.
See Also:
setNullReplace(java.lang.String)

setBlankReplace

public void setBlankReplace(String val)
Set the string value to replace blank strings (zero length) with when converting collections of strings.

Parameters:
val - New String value to assign.
See Also:
getBlankReplace()

getBlankReplace

public String getBlankReplace()
Get the string value to replace blank strings (zero length) with when converting collections of strings.

Returns:
Current String value assigned.
See Also:
setBlankReplace(java.lang.String)

setNullSkipped

public void setNullSkipped(boolean val)
Set whether we should we skip (omit) 'null' string objects when working with collections.

Parameters:
val - New boolean value to assign.
See Also:
isNullSkipped()

isNullSkipped

public boolean isNullSkipped()
Should we skip (omit) 'null' string objects when working with collections?

Returns:
Current boolean value assigned.
See Also:
setNullSkipped(boolean)

setBlankSkipped

public void setBlankSkipped(boolean val)
Set whether we should we skip (omit) 'blank' string objects when working with collections.

Parameters:
val - New boolean value to assign.
See Also:
isBlankSkipped()

isBlankSkipped

public boolean isBlankSkipped()
Should we skip (omit) 'blank' string objects when working with collections?

Returns:
Current boolean value assigned.
See Also:
setBlankSkipped(boolean)

setComparator

public void setComparator(Comparator val)
Set the comparator to use when sorting strings.

Parameters:
val - New Comparator value to assign.
See Also:
getComparator()

getComparator

public Comparator getComparator()
Get the comparator to use when sorting strings.

Returns:
Current Comparator value assigned - never returns null (defaults to self).
See Also:
setComparator(java.util.Comparator)

setDescending

public void setDescending(boolean val)
Set whether a descending sort should be generated.

This method can be used to control whether the comparator is to be used for a ascending or descending sort. At the time of construction, a ascending sort is assumed ("a", "b", "c", ...). If you pass true to this method, you'll get a descending sort ("z", "y", "x", ...).

Parameters:
val - false for standard ascending compare, true to reverse the sort to create a descending compare.
See Also:
isDescending()

isDescending

public boolean isDescending()
Is a descending sort to be generated set?

Returns:
Current boolean value assigned.
See Also:
setDescending(boolean)

setCaseIgnored

public void setCaseIgnored(boolean val)
Set whether case should be ignored when making string comparisons.

Parameters:
val - New boolean value to assign.
See Also:
isCaseIgnored()

isCaseIgnored

public boolean isCaseIgnored()
Is case ignored when making string comparisons?

Returns:
Current boolean value assigned.
See Also:
setCaseIgnored(boolean)

compare

public int compare(Object o1,
                   Object o2)
            throws ClassCastException
Compare the String representations of two objects.

This is the method that all Comparator's must implement. It determines if one object (o1) is less than, equal to or greater than another object (o2).

This method can be overridden by derived classes. This implementation uses the following approach:

Specified by:
compare in interface Comparator
Parameters:
o1 - Object to compare against.
o2 - Object to compare against o1.
Returns:
0 if equal, less than 0 if o1 < o2, greater than 0 if o1 > o2.
Throws:
ClassCastException
Since:
1.0
See Also:
setDescending(boolean), setCaseIgnored(boolean)


Copyright 1998-1998-2006 null. All Rights Reserved.