Java UTF8 Encode utf8Code(String str)

Here you can find the source of utf8Code(String str)

Description

Get the literal presentation of utf8 string

License

Open Source License

Parameter

Parameter Description
str a parameter

Declaration

public static String utf8Code(String str) 

Method Source Code

//package com.java2s;
//License from project: GNU General Public License 

public class Main {
    /**/*from  ww  w. j av a2  s  .  co  m*/
     * Get the literal presentation of utf8 string
     * @param str
     * @return
     */
    public static String utf8Code(String str) {
        StringBuilder ostr = new StringBuilder();
        String hex;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if ((ch >= 0x0020) && (ch <= 0x007e)) {// Does the char need to be converted to unicode?
                ostr.append(ch);
            } else {
                ostr.append("\\u"); // standard unicode format.
                hex = Integer.toHexString(ch & 0xFFFF); // Get hex value of the char.
                for (int j = 0; j < 4 - hex.length(); j++) // Prepend zeros because unicode requires 4 digits
                    ostr.append("0");
                ostr.append(hex.toLowerCase()); // standard unicode format.
            }
        }
        return ostr.toString(); //Return the stringbuffer cast as a string.
    }
}

Related

  1. toUTF8Bytes(final String s)
  2. toUTF8Bytes(String src)
  3. toUTF8Bytes(String string)
  4. toUTF8InputStream(String str)
  5. toUTF8String(byte[] b, int offset, int length)
  6. Utf8codeCheck(String text)
  7. utf8Encode(final Collection col)
  8. utf8Encode(final String s)
  9. utf8Encode(final String value)