gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:46:02 25 4
gpt4 key购买 nike

我有一个字符串

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]

关于java - 如何将字符串中的 UTF-8 替换为类似的拉丁字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36309523/

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