gpt4 book ai didi

java - 如何在java中将字符串UTF-8转换为ANSI?

转载 作者:行者123 更新时间:2023-11-30 03:54:31 26 4
gpt4 key购买 nike

我有一个 UTF-8 格式的字符串。我想将其转换为干净的 ANSI 格式。如何做到这一点?

最佳答案

您可以使用像这里这样的 java 函数将 UTF-8 转换为 ISO_8859_1(这似乎是 ANSI 的子集):

private static String convertFromUtf8ToIso(String s1) {
if(s1 == null) {
return null;
}
String s = new String(s1.getBytes(StandardCharsets.UTF_8));
byte[] b = s.getBytes(StandardCharsets.ISO_8859_1);
return new String(b, StandardCharsets.ISO_8859_1);
}

这是一个简单的测试:

String s1 = "your utf8 stringáçﬠ";
String res = convertFromUtf8ToIso(s1);
System.out.println(res);

打印出:

your utf8 stringáç?

字符会丢失,因为它无法用 ISO_8859_1 表示(以 UTF-8 编码时有 3 个字节)。 ISO_8859_1 可以表示 áç

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

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