Anyone have a better way to implement the below code...
Sorry about the weird formatting, but the word wrap munges it...
/**
* This method will capitalize a String.
*
* It is assumed that the input String is a person's name. The
following rules are applied:
* <ul>
* <li>First letter is capitalized:
* <ul>
* <li>bill becomes Bill</li>
* </ul>
* </li>
* <li>mc and mac are respected:
* <ul>
* <li>mcphersen becomes McPhersen</li>
* <li>macdonald becomes MacDonald</li>
* </ul>
* </li>
* </ul>
*
* @param theValue
* @return String
*/
public static String properName(String theValue)
{
try
{
return
convertProperName(theValue.trim().toLowerCase());
}
catch (NullPointerException e)
{
return "";
}
}
/**
* This method will capitalize a String.
*
* It is assumed that the input String contains one or more person's
names. The following rules are applied:
* <ul>
* <li>First letter of each name is capitalized:
* <ul>
* <li>bill smith becomes Bill Smith</li>
* </ul>
* </li>
* <li>mc and mac are respected:
* <ul>
* <li>bill mcphersen becomes Bill McPhersen</li>
* <li>bill macdonald becomes Bill MacDonald</li>
* <li>bill a. macdonald becomes Bill A. MacDonald</li>
* <li>bill a.t. macdonald becomes Bill A.T. MacDonald</li>
* </ul>
* </li>
* </ul>
*
* @param theValue
* @return String
*/
public static String properNames(String theValue)
{
StringTokenizer names;
try
{
names = new
StringTokenizer(theValue.trim().toLowerCase());
}
catch (NullPointerException e)
{
return "";
}
StringBuffer out = new StringBuffer();
boolean moreNames = false;
String name;
while (names.hasMoreElements())
{
if (moreNames)
out.append(' ');
name = (String) names.nextElement();
if (name.indexOf(".") > 0) // contains a period, so
might be one or more initials
{
StringTokenizer initials = new
StringTokenizer(name, ".");
while (initials.hasMoreElements())
{
name = (String)
initials.nextElement();
out.append(convertProperName(name));
out.append('.');
}
}
else
out.append(convertProperName(name));
moreNames = true;
}
return out.toString();
}
/**
* This method actually does the proper name conversion.
*
* It is private because it assumes that:
* - the passed value is not null
* - the name has been converted to lower case
*
* It is used from:
* - properName
* - properNames
*
* @param theValue
* @return
*/
private static String convertProperName(String theValue)
{
char charArray[] = theValue.toCharArray();
StringBuffer out = new StringBuffer(theValue.length() + 1);
int nextCapital;
// handle the special class of names such as:
// - McDonald
// - MacDonald
if (theValue.startsWith("mc"))
nextCapital = 2;
else if (theValue.startsWith("mac"))
nextCapital = 3;
else
nextCapital = -1; // no capital within name
for (int c = 0; c < charArray.length; c++)
if (c == 0 || c == nextCapital)
out.append(Character.toUpperCase(charArray[c]));
else
out.append(charArray[c]);
return out.toString();
}