Friday, April 24, 2009

The Whitespace Stripper

This is yet another method written in Java that deals with string manipulations. I have written a method that returns the same result of the regular expression [\s*]. The regular expression "[\s*]" translated into plain English is "Match 0 or more of the preceeding whitespace character (spaces, tabs, line breaks) in the set".

Below is the suggested solution in Java to strip off whitespace characters without using regular expressions. The code itself is quite straight forward. "NicholasKey" will be returned as the result of this method with the given input "Nicholas Key".

public static String stripWhiteSpace(String text){
StringBuffer cleanText = new StringBuffer();
int len = text.length();
for (int i=0; i<len; i++) {
if (text.charAt(i) != ' ') {
cleanText.append(text.charAt(i));
}
}
return cleanText.toString();
}
Update: The code is also available in Python in this entry

0 comments:

Post a Comment