Convert Unicode in format \u1234 to String - Java java.lang

Java examples for java.lang:String Unicode

Description

Convert Unicode in format \u1234 to String

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String s = "\u1234";
        System.out.println(deUnicode(s));
    }// www . j  av  a 2  s .co  m

    public static String deUnicode(String s) {
        StringBuilder sb = new StringBuilder(s.length());
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == '\\' && chars[i + 1] == 'u') {
                char cc = 0;
                for (int j = 0; j < 4; j++) {
                    char ch = Character.toLowerCase(chars[i + 2 + j]);
                    if ('0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f') {
                        cc |= (Character.digit(ch, 16) << (3 - j) * 4);
                    } else {
                        cc = 0;
                        break;
                    }
                }
                if (cc > 0) {
                    i += 5;
                    sb.append(cc);
                    continue;
                }
            }
            sb.append(c);
        }
        return sb.toString();
    }
}

Related Tutorials