gpt4 book ai didi

java - Android - 适用于所有语言的正确字符串编码

转载 作者:行者123 更新时间:2023-11-29 21:20:06 27 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序,涉及显示来自多种语言的字符串。例如,中文可能需要 UTF-8 编码,而日语可能需要 ShiftJS。我想知道是否有适用于这种情况的通用解决方案来正确显示所有(或大多数)语言字符串?

谢谢!

最佳答案

仅当您从外部源(例如文件)构造 String 对象以及将 String 对象转换为外部形式(例如文件)时,您才需要担心 UTF-8 或 Shift_JIS。相反,如果您已经有一个 String 对象,则不必担心 UTF-8 或 Shift_JIS。

构造字符串对象时:

// HIRAGANA LETTER A (U+3042), encoded in UTF-8.
byte[] rawDataEncodedInUTF8 = { (byte)0xE3, (byte)0x81, (byte)0x82 };
// Convert to a String object from the bytes.
String a1 = new String(rawDataEncodedInUTF8, "UTF-8");

// HIRAGANA LETTER A (U+3042), encoded in Shift_JIS.
byte[] rawDataEncodedInShiftJIS = { (byte)0x82, (byte)0xA0 };
// Convert to a String object from the bytes.
String a2 = new String(rawDataEncodedInShiftJIS, "Shift_JIS");

// Both a1 and a2 represent HIRAGANA LETTER A (U+3042).
// So, a1.equals(a2) is true.

// String.charAt(int) returns a character at the index in
// UTF-16BE, so c here is 0x3042. Note that the meaning of
// 'U+3042' and that of '0x3042 in UTF-16BE' are different.
char c = a1.charAt(0);

构建外部表单时:

String text = ...;

byte[] rawDataEncodedInUTF8 = text.getBytes("UTF-8");
byte[] rawDataEncodedInShiftJIS = text.getBytes("Shift_JIS");

首先,您需要了解 (1) Unicode 及其编码 (UTF-8/UTF-16BE/UTF-16LE/...) 之间的区别以及 (2) Java 使用 Unicode。然后,我建议您在将数据保存到文件、数据库和任何其他外部位置时使用 UTF-8。

关于java - Android - 适用于所有语言的正确字符串编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20835651/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com