/** Demo of alternate methods for sanitizing a string */ public class SanitaryString { /* Uses no data structure */ private static String bonehead(String suspect) { StringBuffer result = new StringBuffer(); // Examine each character in the suspect string for (int i=0; i= 'a' && current <= 'z' || current >= 'A' && current <= 'Z' || current >= '0' && current <= '9' || current == '.' || current == '_') { result.append(current); } } return result.toString(); } /* Uses a linear search: indexOf() */ private static String sanitize(String suspect) { // allow alphanumerics or period or underline final String kAllowedCharacters = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "._"; StringBuffer result = new StringBuffer(); // Examine each character in the suspect string for (int i=0; i= 0) { result.append(current); } } return result.toString(); } // Uses a lookup table (for ASCII characters) private static String lookup(String suspect) { // allow alphanumerics or period or underline final boolean[] kAllowedCharacters = { false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false,false,false, // . 0 1 false,false,false,false,false,false,true, false,true, true, // 2 3 4 5 6 7 8 9 true, true, true, true, true, true, true, true, false,false, // A B C D E false,false,false,false,false,true, true, true, true, true, // F G H I J K L M N O true, true, true, true, true, true, true, true, true, true, // P Q R S T U V W X Y true, true ,true ,true ,true ,true ,true ,true, true, true, // Z _ a b c true, false,false,false,false,true, false,true, true, true, // d e f g h i j k l m true, true, true, true, true, true, true, true, true, true, // n o p q r s t u v w true, true, true, true, true, true, true, true, true, true, // x y z true, true, true, false,false,false,false,false }; StringBuffer result = new StringBuffer(); // Examine each character in the suspect string for (int i=0; i