java - 如何在 Java 中将 UTF-8 表示解析为字符串?

标签 java utf-8 ascii

给定以下代码:

String tmp = new String("\\u0068\\u0065\\u006c\\u006c\\u006f\\u000a");

String result = convertToEffectiveString(tmp); // result contain now "hello\n"

JDK 是否已经提供了一些用于执行此操作的类? 有这样做的图书馆吗? (最好在maven下)

我尝试使用 ByteArrayOutputStream 但没有成功。

最佳答案

这有效,但仅适用于 ASCII。如果您使用 ASCCI 范围之外的 unicode 字符,那么您将遇到问题(因为每个字符都被填充到一个字节中,而不是 UTF-8 允许的完整单词中)。您可以执行下面的类型转换,因为您知道如果您保证输入基本上是 ASCII(正如您在评论中提到的那样),UTF-8 将不会溢出一个字节。

package sample;

import java.io.UnsupportedEncodingException;

public class UnicodeSample {
    public static final int HEXADECIMAL = 16;

    public static void main(String[] args) {

        try {
            String str = "\\u0068\\u0065\\u006c\\u006c\\u006f\\u000a";

            String arr[] = str.replaceAll("\\\\u"," ").trim().split(" ");
            byte[] utf8 = new byte[arr.length];

            int index=0;
            for (String ch : arr) {
                utf8[index++] = (byte)Integer.parseInt(ch,HEXADECIMAL);
            }

            String newStr = new String(utf8, "UTF-8");
            System.out.println(newStr);

        }
        catch (UnsupportedEncodingException e) {
            // handle the UTF-8 conversion exception
        }
    }
}

这是解决仅使用 ASCII 字符问题的另一种解决方案。这将适用于 UTF-8 范围内的任何 unicode 字符,而不是仅在该范围的前 8 位中使用 ASCII。感谢 deceze 提出的问题。你让我更多地思考问题和解决方案。

package sample;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class UnicodeSample {
    public static final int HEXADECIMAL = 16;

    public static void main(String[] args) {

        try {
            String str = "\\u0068\\u0065\\u006c\\u006c\\u006f\\u000a\\u3fff\\uf34c";

            ArrayList<Byte> arrList = new ArrayList<Byte>();
            String codes[] = str.replaceAll("\\\\u"," ").trim().split(" ");

            for (String c : codes) {

                int code = Integer.parseInt(c,HEXADECIMAL);
                byte[] bytes = intToByteArray(code);

                for (byte b : bytes) {
                    if (b != 0) arrList.add(b);
                }
            }

            byte[] utf8 = new byte[arrList.size()];
            for (int i=0; i<arrList.size(); i++) utf8[i] = arrList.get(i);

            str = new String(utf8, "UTF-8");
            System.out.println(str);
        }
        catch (UnsupportedEncodingException e) {
            // handle the exception when
        }
    }

    // Takes a 4 byte integer and and extracts each byte
    public static final byte[] intToByteArray(int value) {
        return new byte[] {
                (byte) (value >>> 24),
                (byte) (value >>> 16),
                (byte) (value >>> 8),
                (byte) (value)
        };
    }
}

关于java - 如何在 Java 中将 UTF-8 表示解析为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9286794/

相关文章:

java - 当我平移 map 时,Google map 叠加层不会移动

java - 如何在java中的arraylist中添加异常

java - 比较转换 ISO8601 兼容日期与 Java 日期?

utf-8 - HTTP 请求 header 是否必须采用 UTF-8 编码?

python - Pyserial 格式 - 超过 127 的字节返回为 2 个字节,而不是一个

powershell - 如何将 ASCII Art 输出到控制台?

java - 系统属性 : user. 地区或用户.国家

php - UTF-8 和 HTML 实体

android - 如何编码 NDEF 消息

C程序无法识别空格字符