This class contains utilities for doing String Manipulation/Conversion not provided by standards Java classes
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Vector;
import java.util.StringTokenizer;
import java.util.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.text.ParsePosition;
import java.text.ParseException;
//////////////////////////////////////////////////////////////////////////
/**
* This class contains utilities for doing String Manipulation/Conversion
* not provided by standards Java classes.<p>
* <b>Examples:</b> <p>
* <pre>
* String arr[] = {"1", "2", "3"};
* StringUtils.arrayToString(arr, ","); // Returns "1, 2, 3"
*
* String dateVal = "31-01-2001";
* StringUtils.changeDateFormat(dateVal, "dd-MM-yyyy", "MM-dd-yyyy");
* // Returns "01-31-2001"
*
* String dateVal = new Date();
* StringUtils.dateToString(dateVal, StringUtils.DATE_FORMAT, null);
* // Returns "2001-09-24 12:00:00.123"
*
* StringUtils.enumToArray(enum);
*
* String str = "Swapnil Rupji";
* StringUtils.replaceString(str, " ", ", "); // Returns "Swapnil, Rupji"
*
* String str = "Hi ?! Your employee no is ?";
* String replaceWith[] = {"Swapnil", "12345"};
* StringUtils.replaceString(str, "?", replaceWith);
* // Returns "Hi Swapnil! Your employee no is 12345"
*
* String str = "1, 2, 3";
* StringUtils.stringToArray(str, ", "); // Returns array {"1", "2", "3"}
*
* StringUtils.stringToDate("12-12-2001", "MM-dd-yyyy", (Date)null);
* // Returns Date object with the date of 12th December 2001
* </pre><p>
* @author Saravanan Nachimuthu
*/
//////////////////////////////////////////////////////////////////////////
public class StringUtils
{
///////////////////////////////////////////////////////////////////////
// P U B L I C I N T E R F A C E
///////////////////////////////////////////////////////////////////////
/**
* Default Date Format "yyyy-MM-dd hh:mm:ss.S"
*/
///////////////////////////////////////////////////////////////////////
public static String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss.S";
///////////////////////////////////////////////////////////////////////
/**
* This method replaces all the occurences of the search string with
* the replace string in the string passed as the first argument to
* the method.
*
* @param inString The String to operate on.
* @param searchStr The Search string to search for in inString.
* @param replaceStr The String to be replaced in the inString for the
* occurences of searchStr.
* @return The inString replaced with replaceStr for all the occurences
* of searchStr.
*/
///////////////////////////////////////////////////////////////////////
public static String replaceString
(
String inString,
String searchStr,
String replaceStr
)
{
String retStr = inString; // Holds the return String
String tempStr = new String(); // Temporary buffer to hold the return string
int indexPos = 0; // Current position of the search String
int prevPos = 0; // Previous position of the search String
// If the input string or search string is null then don't proceed.
if ( inString == null || searchStr == null ) return retStr;
// Replace the search string with the replace string for all the occurrences in inString
while ( (indexPos = inString.indexOf(searchStr, indexPos)) >= 0 )
{
tempStr = tempStr + inString.substring(prevPos, indexPos) + replaceStr;
indexPos = indexPos + searchStr.length();
prevPos = indexPos;
}
// Append the remaining characters in the String to the temporary buffer.
tempStr = tempStr + inString.substring(prevPos);
// If everything went fine then assigne the temporary buffer to the return String.
if ( tempStr.trim().length() > 0 )
retStr = tempStr;
return retStr;
}
public static String replaceStringEPP(String str) // "C A K 2 0 3 C "
{
String temp = "";
for(int i=0; i<str.length();)
{
temp = temp+str.substring(i,i+1);
i=i+2;
}
return temp;
}
///////////////////////////////////////////////////////////////////////
/**
* This method replaces the string identified by the second parameter
* with the strings in the third parameter in the sequence from left
* to right of the first parameter string.
*
* @param str The String to be operated on.
* @param searchFor The string to be searched for.
* @param replaceWith The string to be replaced with.
* @return The replaced string for the occurences of searchFor as described
* in the replaceWith array.
*/
///////////////////////////////////////////////////////////////////////
public static String replaceString
(
String str,
String searchFor,
String replaceWith[]
)
{
String retStr = new String(); // The replaced string
// return if any of the parameters is null
if ( searchFor == null || str == null || replaceWith == null ) return str;
int prevIndex = 0; // The previous index for substring
int lastIndex = 0; // the index to search from for the Search string
int searchLength = searchFor.length(); // Length of the search string
// Replace all the string occurences with the array elements of replaceWith
for ( int counter = 0; counter < replaceWith.length; counter++ )
{
/*
* Logic in brief:
*
* Search for the searchFor string in str.
* Put the string before the last occurence into the retStr.
* Add the replaceWith element string.
* Search for the rest of the str for searchFor string.
*
*/
prevIndex = lastIndex;
lastIndex = str.indexOf(searchFor, lastIndex);
if ( lastIndex < 0 )
{
lastIndex = prevIndex;
break;
}
retStr = retStr + str.substring(prevIndex, lastIndex) + replaceWith[counter];
lastIndex = lastIndex + searchLength;
}
// Add the remaining characters to the retStr, if any.
retStr = retStr + str.substring(lastIndex);
return retStr;
}
///////////////////////////////////////////////////////////////////////
/**
* This method converts the string array into string with all
* the strings in tha array delimited by the delimiter.
*
* @param arrayElem The string array to be converted to string.
* @param delimiter The delimiter to be put between the array elements.
* @return The string with the delimiters.
*/
///////////////////////////////////////////////////////////////////////
public static String arrayToString
(
String arrayElem[],
String delimiter
)
{
String retValue = new String(); // Holds the return string
String delim = delimiter; // Holds the delimiter
// Initialize the delimiter string if null
if ( delim == null ) delim = new String("");
// Put the delimiter in between the elements of the array
if ( arrayElem != null )
{
for ( int counter = 0; counter < arrayElem.length; counter++ )
{
retValue = retValue + arrayElem[counter];
// If not the last element then put the delimiter
if ( counter != ( arrayElem.length - 1 ) )
{
retValue = retValue + delim;
}
}
}
return retValue;
}
///////////////////////////////////////////////////////////////////////
/**
* This method converts the string into string array with all
* the strings serparated by the delimiter.
*
* @param stringElem The string to be converted to string array.
* @param delimiter The delimiter to distinguish the array elements.
* @return The string array.
*/
///////////////////////////////////////////////////////////////////////
public static String[] stringToArray
(
String stringElem,
String delimiter
)
{
StringTokenizer st = new StringTokenizer(stringElem, delimiter);
String retValue[] = new String[st.countTokens()]; // Holds the return string
String delim = delimiter; // Holds the delimiter
// Initialize the delimiter string if null
if ( delim == null ) delim = new String("");
int i = 0;
// Sperate the string using the delimiter
while ( st.hasMoreTokens() )
{
retValue[i++] = st.nextToken();
}
return retValue;
}
///////////////////////////////////////////////////////////////////////
/**
* Returns the element pointing to the specified row, column in the
* specified format.
*
* @param xPos The row number.
* @param colName The Column Name.
* @return The column element.
*/
///////////////////////////////////////////////////////////////////////
public java.util.Date stringToDate
(
String dateString,
String format,
java.util.Date def
)
{
if (dateString == null || dateString.trim().length() <= 0)
{
return def;
}
if ( format == null || format.trim().length() == 0 )
{
format = DATE_FORMAT;
}
// Set the Date Format for the vaules in the column specified
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.parse(dateString, new ParsePosition(0));
}
/**
* This method converts the string date to a particular format.
*
* @param dateString The String to operate on.
* @param srcFormat The date Format contained in the String.
* @param destFormat The format to be converted to.
* @return Formatted Date String if successful, null otherwise.
*/
public static String changeDateFormat
(
String dateString,
String srcFormat,
String destFormat
)
{
if ( srcFormat == null || destFormat == null
|| srcFormat.trim().equals("") || destFormat.trim().equals("") )
{
return "";
}
// Set the Date Format for the vaules in the column specified
SimpleDateFormat dateFormat = new SimpleDateFormat(srcFormat);
if ( dateString == null || dateFormat == null
|| dateString.trim().equals("") )
{
return "";
}
// Get date as per the format
java.util.Date dateVal = dateFormat.parse(dateString, new ParsePosition(0));
dateFormat = new SimpleDateFormat(destFormat);
return dateFormat.format(dateVal);
}
///////////////////////////////////////////////////////////////////////
/**
* This method converts the date to a particular format.
*
* @param dateString The date to operate on.
* @param format The date Format.
* @return Formatted Date if successful, null otherwise.
*/
///////////////////////////////////////////////////////////////////////
public static String dateToString( java.util.Date dateVal,
String format,
String def)
{
if ( format == null || format.trim().equals("") )
{
format = DATE_FORMAT;
}
// Set the Date Format for the vaules in the column specified
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
if ( dateVal == null )
{
return def;
}
return dateFormat.format(dateVal);
}
///////////////////////////////////////////////////////////////////////
/**
* This method converts the Strings in the enumeration into a String
* array.
*
* @param enumeration The enumerations that contains the String objects.
* @return String array from the Enumeration. Null if the parameter is null.
*/
///////////////////////////////////////////////////////////////////////
public static String[] enumToArray(Enumeration enumeration)
{
String retArray[] = null;
// Initialize a Vector to hold the contents of the Enumeration
Vector vector = new Vector();
// Return null if the parameter is null
if ( enumeration == null )
{
return retArray;
}
// Get all the String objects into the Vector
while (enumeration.hasMoreElements())
{
vector.addElement((String)enumeration.nextElement());
}
retArray = new String[vector.size()];
// Fetch and Return the array from the Vector
vector.copyInto(retArray);
return retArray;
}
///////////////////////////////////////////////////////////////////////
/**
* This method returns a value associated with a key from the Hashtable
* passed to it. Returns the default value passed to this method if the
* key is not found in the Hashtable.<p>
*
* @param hash The Hashtable to return the requested value from.<p>
* @param key The Key in the Hashtable to get the value for.<p>
* @param key The Key in the Hashtable to get the value for.<p>
* @return The Object value found in the Hashtable for the key otherwise
* return the default value.<p>
*/
///////////////////////////////////////////////////////////////////////
public static Object hashGet(Hashtable hash, Object key, Object defValue)
{
Object retVal = defValue;
if ( hash.containsKey(key) )
{
retVal = hash.get(key);
}
return retVal;
}
///////////////////////////////////////////////////////////////////////
/**
* This method returns a value associated with a key from the Hashtable
* passed to it. Returns the default value passed to this method if the
* key is not found in the Hashtable.<p>
*
* @param hash The Hashtable to return the requested value from.<p>
* @param key The Key in the Hashtable to get the value for.<p>
* @param key The Key in the Hashtable to get the value for.<p>
* @return The String value found in the Hashtable for the key otherwise
* return the default value.<p>
*/
///////////////////////////////////////////////////////////////////////
public static String hashGet(Hashtable hash, Object key, String defValue)
{
String retVal = defValue;
if ( hash.containsKey(key) )
{
retVal = ((String)hash.get(key)).trim();
if ( retVal.length() <= 0)
{
retVal = defValue;
}
}
return retVal;
}
///////////////////////////////////////////////////////////////////////
/**
* This method converts the date in String format to a java.sql.Date format.<p>
*
* @param dateString The date to operate on.
* @param format The date Format.
* @param def The default date if the Format is not specified.<p>
* @return Formatted Date if successful, null otherwise.
*/
///////////////////////////////////////////////////////////////////////
public static java.sql.Date stringToSqlDate(
String dateString,
String format,
java.sql.Date def)
{
if (dateString == null || dateString.trim().length() <= 0)
{
return def;
}
if ( format == null || format.trim().length() == 0 )
{
format = DATE_FORMAT;
}
// Set the Date Format for the vaules in the column specified
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
java.util.Date dt = dateFormat.parse(dateString, new ParsePosition(0));
return java.sql.Date.valueOf(dateToString(dt, "yyyy-MM-dd", ""));
}
///////////////////////////////////////////////////////////////////////
/**
* This method converts the date in String format to a Timestamp format.<p>
*
* @param dateString The date to operate on.
* @param format The date Format.
* @param def The default date if the Format is not specified.<p>
* @return Formatted Date if successful, null otherwise.
*/
///////////////////////////////////////////////////////////////////////
public static Timestamp stringToTimestamp(
String dateString,
String format,
Timestamp def)
{
if (dateString == null || dateString.trim().length() <= 0)
{
return def;
}
if ( format == null || format.trim().length() == 0 )
{
format = DATE_FORMAT;
}
// Set the Date Format for the vaules in the column specified
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
java.util.Date dt = dateFormat.parse(dateString, new ParsePosition(0));
return Timestamp.valueOf(dateToString(dt, "yyyy-MM-dd hh:mm:ss.S", ""));
}
///////////////////////////////////////////////////////////////////////
/**
* This method converts the date to a particular format.
*
* @param dt The date to operate on.
* @param def The Timestamp if dt is null.
* @return Formatted Date if successful, null otherwise.
*/
///////////////////////////////////////////////////////////////////////
public static Timestamp dateToTimestamp( Date dt, Timestamp def )
{
if (dt == null )
{
return def;
}
return Timestamp.valueOf(dateToString(dt, "yyyy-MM-dd hh:mm:ss.S", ""));
}
///////////////////////////////////////////////////////////////////////
/**
* This method converts the date to a particular format.
*
* @param dt The date to operate on.
* @param def The default value if dt is null.
* @return Formatted Date if successful, null otherwise.
*/
///////////////////////////////////////////////////////////////////////
public static java.sql.Date convertDate( Date dt, java.sql.Date def )
{
if (dt == null )
{
return def;
}
return java.sql.Date.valueOf(dateToString(dt, "yyyy-MM-dd", ""));
}
///////////////////////////////////////////////////////////////////////
/**
* This method parses String passed.<p>
*
* @param arg The value to be parsed.<p>
* @return The trimmed value of arg. Returns null otherwise.<p>
*/
///////////////////////////////////////////////////////////////////////
public static String parseString(String arg)
{
return parseString(arg, null);
}
///////////////////////////////////////////////////////////////////////
/**
* This method parses the String value passed.<p>.
*
* @param arg The value to be parsed.<p>
* @return True if arg contains any value among "y", "yes" or "true"
* irrespective of the case.Returns false otherwise.<p>
*/
///////////////////////////////////////////////////////////////////////
public static boolean parseBoolean(String arg)
{
return parseBoolean(arg, false);
}
///////////////////////////////////////////////////////////////////////
/**
* This method parses the String value passed.<p>.
*
* @param arg The value to be parsed.<p>
* @return long value for the arg. -1 otherwise.<p>
*/
///////////////////////////////////////////////////////////////////////
public static long parseLong(String arg)
{
return parseLong(arg, -1);
}
///////////////////////////////////////////////////////////////////////
/**
* This method parses the String value passed.<p>.
*
* @param arg The value to be parsed.<p>
* @return integer value for the arg. -1 otherwise.<p>
*/
///////////////////////////////////////////////////////////////////////
public static int parseInt(String arg)
{
return parseInt(arg, -1);
}
///////////////////////////////////////////////////////////////////////
/**
* This method parses the String value passed.<p>.
*
* @param arg The value to be parsed.<p>
* @return float value for the arg. -1.0 otherwise.<p>
*/
///////////////////////////////////////////////////////////////////////
public static float parseFloat(String arg)
{
return parseFloat(arg, (float)0.0);
}
///////////////////////////////////////////////////////////////////////
/**
* This method rounds a float to a predefined length.<p>.
*
* @param arg The value to be parsed.<p>
* @return float value for the arg. -1.0 otherwise.<p>
*/
///////////////////////////////////////////////////////////////////////
public static double roundFunc(double a, int b)
{
double num = b;
double _deka_ = 10.0;
double c = Math.pow(_deka_, num);
double d = a*c;
double result1 = java.lang.Math.round(d);
double the_result;
the_result = result1 / c;
return the_result;
}
///////////////////////////////////////////////////////////////////////
/**
* This method parses String passed.<p>
*
* @param arg The value to be parsed.<p>
* @param def The default value.<p>
* @return The trimmed value of arg. Returns def otherwise.<p>
*/
///////////////////////////////////////////////////////////////////////
public static String parseString(String arg, String def)
{
String ret = def;
if ( arg != null && arg.trim().length() > 0 )
{
ret = arg.trim();
}
return ret;
}
///////////////////////////////////////////////////////////////////////
/**
* This method parses the String value passed.<p>.
*
* @param arg The value to be parsed.<p>
* @param def The default value .<p>
* @return True if arg contains any value among "y", "yes" or "true"
* irrespective of the case.Returns def otherwise.<p>
*/
///////////////////////////////////////////////////////////////////////
public static boolean parseBoolean(String arg, boolean def)
{
boolean ret = def;
String val = null;
if ( arg != null && arg.trim().length() > 0 )
{
val = arg.trim();
if ( val.toUpperCase().equals("Y") ||
val.toUpperCase().equals("YES") ||
val.toUpperCase().equals("TRUE") )
{
ret = true;
}
else
{
ret = false;
}
}
return ret;
}
///////////////////////////////////////////////////////////////////////
/**
* This method parses the Boolean value passed.<p>.
*
* @param arg The Boolean value to get the boolean value for.<p>
* @param def The default value .<p>
* @return boolean value of arg. If arg is null returns def.<p>
*/
///////////////////////////////////////////////////////////////////////
public static boolean parseBoolean(Boolean arg, boolean def)
{
boolean ret = def;
if ( arg != null )
{
ret = arg.booleanValue();
}
return ret;
}
///////////////////////////////////////////////////////////////////////
/**
* This method parses the String value passed.<p>.
*
* @param arg The value to be parsed.<p>
* @param def The default value.<p>
* @return long value for the arg. def otherwise.<p>
*/
///////////////////////////////////////////////////////////////////////
public static long parseLong(String arg, long def)
{
long ret = def;
if ( arg != null && arg.trim().length() > 0 )
{
ret = Long.parseLong(arg);
}
return ret;
}
///////////////////////////////////////////////////////////////////////
/**
* This method parses the String value passed.<p>.
*
* @param arg The value to be parsed.<p>
* @param def The default value.<p>
* @return integer value for the arg. def otherwise.<p>
*/
///////////////////////////////////////////////////////////////////////
public static int parseInt(String arg, int def)
{
int ret = def;
if ( arg != null && arg.trim().length() > 0 )
{
ret = Integer.parseInt(arg);
}
return ret;
}
///////////////////////////////////////////////////////////////////////
/**
* This method parses the String value passed.<p>.
*
* @param arg The value to be parsed.<p>
* @param def The default value.<p>
* @return float value for the arg. def otherwise.<p>
*/
///////////////////////////////////////////////////////////////////////
public static float parseFloat(String arg, float def)
{
float ret = def;
if ( arg != null && arg.trim().length() > 0 )
{
ret = Float.parseFloat(arg);
}
return ret;
}
static class Test
{
public static void main(String[] args)
{
}
}
///////////////////////////////////////////////////////////////////////
// D E F A U L T I N T E R F A C E
///////////////////////////////////////////////////////////////////////
// Define default Constants and Variables for the Class
///////////////////////////////////////////////////////////////////////
// P R I V A T E I N T E R F A C E
///////////////////////////////////////////////////////////////////////
// Define private Constants and Variables for the Class
}