Given the rate that I'm running accross these little horrors, this may become a regular post.
public static String trimLeadingZeros( String trimString )
{
String retVal = trimString;
boolean nonZeroFound = false;
StringBuffer rtnString = new StringBuffer();
if ( trimString != null ) {
for ( int index = 0; index < trimString.length(); index++ ) {
char c = trimString.charAt( index );
if ( c == '0' && nonZeroFound == false ) {
// skip all leading zeros
} else {
nonZeroFound = true;
rtnString.append( c );
}
}
}
if ( rtnString.length() > 0 ) {
retVal = rtnString.toString();
}
return retVal;
}
Obviously this person doesn't have a degree in computer science or they failed out.
- The have an empty if statement, what you're not capable of doing the necessary boolean algebra in your head to invert the conditional, give me a break
- Hey lets scan every character whether you need to or not, making this O(n) where n is the total number of charaters in all strings being scanned (sheesh)
- How many damn variables do you need to do this 5! Could we make this any more complex
- The real shame is that the JDK doesn't have a general strip/trim function, they have a trim whitespace, so why not generalize it.
So in about 5 minutes I put a more general version together which O(f(x)) << O(n), in the general case my version is 2.5 times faster than the horror. For the pathalogical case my versio is only.8 time faster, and for the ideal case we're 3 times faster. This was all done over 1 million iterations using the same string that was 20 characters long.
public static String trimLeadingChar( String trimString, char trimChar )
{
try {
String tempString = trimString;
int offset = 0;
while( tempString.indexOf( trimChar, offset ) == offset )
offset++;
tempString = tempString.substring( offset );
if( tempString.length() == offset )
return trimString;
return tempString;
} catch( NullPointerException ex ) {
return trimString;
}
}
I'm using a very Pythonic idom here, which is to not care about the NullPointerException, so instead of explicitly checking for trimString == null, we just catch the excetption and do no harm. I could have made the while loop empty, but frakly I find that a little bit vulgar.


