encode Unicode string - Android java.lang

Android examples for java.lang:String Unicode

Description

encode Unicode string

Demo Code


//package com.java2s;

public class Main {
    /**//from w  w  w . ja  v  a 2s  .  c o m
     * encode Unicode string
     *
     * @param s s
     * @return string
     */
    public static String encodeUnicodeStr(String s) {
        StringBuilder sb = new StringBuilder(s.length() * 3);
        for (char c : s.toCharArray()) {
            if (c < 256) {
                sb.append(c);
            } else {
                sb.append("\\u");
                sb.append(Character.forDigit((c >>> 12) & 0xf, 16));
                sb.append(Character.forDigit((c >>> 8) & 0xf, 16));
                sb.append(Character.forDigit((c >>> 4) & 0xf, 16));
                sb.append(Character.forDigit((c) & 0xf, 16));
            }
        }
        return sb.toString();
    }
}

Related Tutorials