如何将UTF-8替换为字符串中类似的拉丁字母?

时间:2016-03-30 12:55:05

标签: java ldap

我有一个字符串

s = M\\c3\\a4nager

我想将\\c3\\a4替换为等效的拉丁字符ä 所以String应该是

s = Mänager

我搜索了很多如何在java中做到这一点请帮我一样 我想在我的代码中处理所有这样的UTF-8字符。

1 个答案:

答案 0 :(得分:0)

要取消您可以使用以下代码段

的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]