public static String unicodeEscape(String s){
  if (allAscii(s)) {
    return s;
  }
  StringBuilder sb=new StringBuilder(s.length());
  int len=s.length();
  for (int i=0; i < len; ++i) {
    char ch=s.charAt(i);
    if (ch <= 127) {
      sb.append(ch);
    }
 else {
      sb.append("\\u");
      String hexString=Integer.toHexString(ch);
      int numZerosToPad=4 - hexString.length();
      for (int j=0; j < numZerosToPad; ++j) {
        sb.append('0');
      }
      sb.append(hexString);
    }
  }
  return sb.toString();
}

public static String unicodeEscape ( String s ) { if ( allAscii ( s ) ) { return s ; } StringBuilder sb = new StringBuilder ( s . length ( ) ) ; int len = s . length ( ) ; for ( int i = 0 ; i < len ; ++ i ) { char ch = s . charAt ( i ) ; if ( ch <= 127 ) { sb . append ( ch ) ; } else { sb . append ( "\\u" ) ; String hexString = Integer . toHexString ( ch ) ; int numZerosToPad = 4 - hexString . length ( ) ; for ( int j = 0 ; j < numZerosToPad ; ++ j ) { sb . append ( '0' ) ; } sb . append ( hexString ) ; } } return sb . toString ( ) ; }
replaces each non - ascii character in s with its unicode escape sequence \ \ uxxxx where xxxx is a hex number . existing escape sequences won ' t be affected .
