Improved method for removing duplicate white space
On the principle that constant refactoring is a good thing, I revisited my method for removing duplicate white space from Strings / StringBuffers. The result was extremely positive, a much cleaner and more streamlined method.
private StringBuffer rmDuplicateWS(StringBuffer sb)
{
int currentPos = 0;
char ws = ' ';
// trim the leading whitespace
while(sb.charAt(0) == ws)
{
sb.deleteCharAt(0);
}
// now get the trailing whitespace
while(sb.charAt(sb.length() - 1) == ws)
{
sb.deleteCharAt(sb.length() - 1);
}
// loop until we reach the end, deleting duplicate ws instances
boolean chk = true;
while(chk)
{
if((sb.charAt(currentPos) == ws) && (sb.charAt(currentPos + 1) == ws) )
{sb.deleteCharAt(currentPos);}
else
{currentPos++;}
if(currentPos == sb.length() - 1)
{chk = false;} // exit
}
return sb;
}
Advertisement
Categories: Java
Java, refactoring, String Manipulation, StringBuffer, whitespace