nix, shell, perl, php, mysql and mac os x tips and tricks

Thursday, March 3, 2005

In java, take a string and strip alphanumeric characters

Call it like this:
String newString = reformat(categoryName);
// for stripping strings of non alphanumeric stuff and replacing with +
// should really be a class

public String reformat(String categoryName)
{
StringBuffer reformattedString = new StringBuffer();
if (categoryName != null)
{
char[] chars = categoryName.toCharArray();
for (int ii = 0; ii < chars.length; ii++)
{
if (Character.isLetterOrDigit(chars[ii]))
{
reformattedString.append(chars[ii]);
}
else if (Character.isSpaceChar(chars[ii]))
{
if (reformattedString.length() > 0 && reformattedString.charAt(reformattedString.length() - 1) != '_')
{
reformattedString.append('_');
}
}
}
}
return reformattedString.toString();
}

No comments:

Post a Comment