Java Unicode Create toUnicode(String input)

Here you can find the source of toUnicode(String input)

Description

to Unicode

License

Open Source License

Declaration

public static String toUnicode(String input) 

Method Source Code

//package com.java2s;
/**/*from  w  w  w  . j a  va  2  s.  c  o m*/
 * *****************************************************************************
 * Copyright (c) 2009 Andrey Loskutov. All rights reserved. This program and the
 * accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html Contributor: Andrey Loskutov -
 * initial API and implementation
 * *****************************************************************************
 */

public class Main {
    public static String toUnicode(String input) {
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (!Character.isWhitespace(ch) && ch < 0x20 || ch > 0x7e) {
                ret.append("\\u");
                // requires 1.5 VM
                // ret.append(String.format("%1$04x", new Object[] { Integer.valueOf(ch) }));
                ret.append(leading4Zeros(Integer.toHexString(ch)));
            } else {
                ret.append(ch);
            }
        }
        return ret.toString();
    }

    /**
     * @param hexString max 4 characters length
     * @return same string with leading zeros
     */
    private static char[] leading4Zeros(String hexString) {
        char[] chars = "0000".toCharArray();
        int length = hexString.length();
        hexString.getChars(0, length, chars, 4 - length);
        return chars;
    }
}

Related

  1. getUnicodeString(byte bytes[], int offset, int len)
  2. getUnicodeString(byte[] d, int length, int pos)
  3. getUnicodeText(Object text)
  4. toUnicode(char c)
  5. toUnicode(final String toUnicode, final boolean toLowerCase)
  6. toUnicode(String input)
  7. toUnicode(String input)
  8. toUnicode(String original)
  9. toUnicode(String s)