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