read unicode string as character string - Java java.lang

Java examples for java.lang:String Unicode

Description

read unicode string as character string

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String encodedString = "java2s.com";
        System.out.println(readUnicode(encodedString));
    }//from w w w  .  j ava  2 s  .  c o  m

    /**
     * read unicode string as character string
     * @param encodedString
     * @return decodedString
     * @author kenu_at_okjsp.pe.kr
     */
    public static String readUnicode(String encodedString) {
        if (encodedString == null)
            return null;
        String[] part = encodedString.split("&#");
        int idx = 0;
        char decodedChar = 0;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < part.length; i++) {
            idx = part[i].indexOf(';');
            if (idx > 0) {
                int unit;
                String unicodeStr = part[i].substring(0, idx);
                if (unicodeStr.startsWith("x")) {
                    unicodeStr = unicodeStr.substring(1);
                    unit = 16;
                } else {
                    unit = 10;
                }
                decodedChar = (char) Integer.parseInt(unicodeStr, unit);
                part[i] = decodedChar + part[i].substring(idx + 1);
            }
            sb.append(part[i]);
        }
        return sb.toString();
    }
}

Related Tutorials