如何将 UTF-8 替换为字符串中类似的拉丁字母?
How to replace UTF-8 to similar Latin letters in a String?
我有一个字符串
s = M\c3\a4nager
我想用对应的拉丁字符 ä
替换 \c3\a4
所以字符串应该是
s = Mänager
我在 java 中搜索了很多如何做到这一点,请帮我做同样的事情
我想在我的代码中处理所有此类 UTF-8 字符。
要取消转义 LDAP 字符串,您可以使用以下代码段
// import javax.naming.ldap.Rdn;
String escapedValue = "M\c3\a4nager";
Object unescapedValue = Rdn.unescapeValue(escapedValue);
System.out.println("escapedValue = " + escapedValue);
System.out.println("unescapedValue = " + unescapedValue);
产出
escapedValue = M\c3\a4nager
unescapedValue = Mänager
unescapedValue
包含 UTF-8 格式的字符串。如果您需要其他编码,则需要妥善处理。
显示不同编码的字节差异的简单示例。
byte[] latinBytes = ((String)unescapedValue).getBytes(StandardCharsets.ISO_8859_1);
byte[] utf8Bytes = ((String)unescapedValue).getBytes(StandardCharsets.UTF_8);
System.out.println("latin1: " + Arrays.toString(latinBytes));
System.out.println("utf8 : " + Arrays.toString(utf8Bytes));
产出
latin1: [77, -28, 110, 97, 103, 101, 114]
utf8 : [77, -61, -92, 110, 97, 103, 101, 114]
我有一个字符串
s = M\c3\a4nager
我想用对应的拉丁字符 ä
替换 \c3\a4
所以字符串应该是
s = Mänager
我在 java 中搜索了很多如何做到这一点,请帮我做同样的事情 我想在我的代码中处理所有此类 UTF-8 字符。
要取消转义 LDAP 字符串,您可以使用以下代码段
// import javax.naming.ldap.Rdn;
String escapedValue = "M\c3\a4nager";
Object unescapedValue = Rdn.unescapeValue(escapedValue);
System.out.println("escapedValue = " + escapedValue);
System.out.println("unescapedValue = " + unescapedValue);
产出
escapedValue = M\c3\a4nager
unescapedValue = Mänager
unescapedValue
包含 UTF-8 格式的字符串。如果您需要其他编码,则需要妥善处理。
显示不同编码的字节差异的简单示例。
byte[] latinBytes = ((String)unescapedValue).getBytes(StandardCharsets.ISO_8859_1);
byte[] utf8Bytes = ((String)unescapedValue).getBytes(StandardCharsets.UTF_8);
System.out.println("latin1: " + Arrays.toString(latinBytes));
System.out.println("utf8 : " + Arrays.toString(utf8Bytes));
产出
latin1: [77, -28, 110, 97, 103, 101, 114]
utf8 : [77, -61, -92, 110, 97, 103, 101, 114]