static public String filter ( String x , String okChars ) { boolean ok = true ; for ( int pos = 0 ; pos < x . length ( ) ; pos ++ ) { char c = x . charAt ( pos ) ; if ( ! ( Character . isLetterOrDigit ( c ) || ( 0 <= okChars . indexOf ( c ) ) ) ) { ok = false ; break ; } } if ( ok ) { return x ; } // gotta do it StringBuilder sb = new StringBuilder ( x . length ( ) ) ; for ( int pos = 0 ; pos < x . length ( ) ; pos ++ ) { char c = x . charAt ( pos ) ; if ( Character . isLetterOrDigit ( c ) || ( 0 <= okChars . indexOf ( c ) ) ) { sb . append ( c ) ; } } return sb . toString ( ) ; }
Remove any char not alphanumeric or in okChars .