Java Unicode to String unicodeToAscii(String theString)

Here you can find the source of unicodeToAscii(String theString)

Description

unicode To Ascii

License

Open Source License

Declaration

public static String unicodeToAscii(String theString) 

Method Source Code

//package com.java2s;

public class Main {
    private static final String specialCharacters = "\t\r\n\f";
    /** A table of hex digits */
    private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };

    public static String unicodeToAscii(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len * 2);

        for (int x = 0; x < len;) {
            aChar = theString.charAt(x++);
            switch (aChar) {
            case '\\':
                outBuffer.append('\\');
                outBuffer.append('\\');
                continue;
            case '\t':
                outBuffer.append('\\');
                outBuffer.append('t');
                continue;
            case '\n':
                outBuffer.append('\\');
                outBuffer.append('n');
                continue;
            case '\r':
                outBuffer.append('\\');
                outBuffer.append('r');
                continue;
            case '\f':
                outBuffer.append('\\');
                outBuffer.append('f');
                continue;
            default:
                if ((aChar < 20) || (aChar > 127)) {
                    outBuffer.append('\\');
                    outBuffer.append('u');
                    outBuffer.append(toHex((aChar >> 12) & 0xF));
                    outBuffer.append(toHex((aChar >> 8) & 0xF));
                    outBuffer.append(toHex((aChar >> 4) & 0xF));
                    outBuffer.append(toHex((aChar >> 0) & 0xF));
                } else {
                    if (specialCharacters.indexOf(aChar) != -1)
                        outBuffer.append('\\');
                    outBuffer.append(aChar);
                }//from   w w  w.j a v  a2s . c om
            }
        }
        return outBuffer.toString();
    }

    /**
     * Convert a nibble to a hex character
     * @param nibble the nibble to convert.
     */
    private static char toHex(int nibble) {
        return hexDigit[(nibble & 0xF)];
    }
}

Related

  1. Unicode2Str(String s)
  2. unicode2String(String unicodeStr)
  3. unicodeStringToPrettyString(String s)
  4. unicodeToAscii(String name, StringBuffer result)
  5. unicodeToString(int unicode)
  6. unicodeToString(String escaped)
  7. unicodeToString(String hex)
  8. unicodeToString(String unicodeStr)