public static String removeWhitespace ( String string ) { if ( string == null || string . length ( ) == 0 ) { return string ; } else { int codePoints = string . codePointCount ( 0 , string . length ( ) ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < codePoints ; i ++ ) { int offset = string . offsetByCodePoints ( 0 , i ) ; int nextCodePoint = string . codePointAt ( offset ) ; if ( ! Character . isWhitespace ( nextCodePoint ) ) { sb . appendCodePoint ( nextCodePoint ) ; } } if ( string . length ( ) == sb . length ( ) ) { return string ; } else { return sb . toString ( ) ; } } }
Removes any whitespace from a String correctly handling surrogate characters