decode UTF8 to String : UTF « Development « Android






decode UTF8 to String

 
class Main {

  public static final String HEX_DIGITS = "0123456789ABCDEF";

  public static char decodeUTF8(String src) {
    if (src == null) {
      throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
    }

    if (!(src.startsWith("\\u") && src.length() <= 6)) {
      throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
    }

    char[] sources = src.substring(2).toCharArray();
    char res = 0;
    for (char nextChar : sources) {
      int digit = HEX_DIGITS.indexOf(Character.toUpperCase(nextChar));
      res = (char) (res * 16 + digit);
    }
    return res;
  }

  public static String decodeUTF8String(String src) {
    StringBuilder sb = new StringBuilder();
    char[] sources = src.toCharArray();
    for (int i = 0; i < sources.length; i++) {
      if (sources[i] == '\\' && i < sources.length - 5
          && sources[i + 1] == 'u') {
        String utf8 = "" + sources[i++] + sources[i++] + sources[i++]
            + sources[i++] + sources[i++] + sources[i];
        sb.append(decodeUTF8(utf8));
        i = i + 5;
      } else {
        sb.append(sources[i]);
      }
    }
    return sb.toString();
  }

}

   
  








Related examples in the same category

1.decode UTF8 to char
2.implements InputFilter
3.UTF 2 GBUtil
4.Load UTF8 encoded file to String
5.UTF8 to Byte Array