【问题标题】:Java: How do I loop through characters in a string that have a surrogate pair and print them?Java:如何遍历具有代理对的字符串中的字符并打印它们?
【发布时间】:2017-03-03 21:45:34
【问题描述】:

我尝试循环遍历字符串中的字符并打印它们。除了 Deseret Long I (????) 之外,所有这些都打印得很好。我不知道是否有其他方法可以做到这一点????打印正确。这是我的代码:

package javaapplication13;
public class JavaApplication13 {
    public static void main(String[] args) {
        String s = "h????y????\u0500";
        System.out.println(s);
        final int length = s.length();
        for (int offset = 0; offset < length;) {
            final int codepoint = s.codePointAt(offset);
            System.out.println((char) (codepoint));
            offset += Character.charCount(codepoint);
        }
    }
}

输出看起来像这样(Netbeans):

run:
h????y????Ԁ
h
䍡
y
Ѐ
Ԁ
BUILD SUCCESSFUL (total time: 0 seconds)

【问题讨论】:

    标签: java string unicode encoding


    【解决方案1】:

    您的问题是由于您尝试将int 转换为char(4 个字节到 2 个字节)引起的。在代理对的情况下,codepoint 变量中的值不能放在一个 char 中。看,它叫pair,因为它是一对字符。我认为最简单的打印方法是使用String.Substring() 方法。或者您可以通过这种方式将其转换为字符数组:char[] ch = Character.toChars(codepoint);,您可以通过简单的new String(ch) 将此数组转换回字符串。

    【讨论】:

    • System.out.println(Character.toChars(codepoint)); 有效!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-06-10
    • 2020-04-28
    • 2019-03-25
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 2022-12-16
    相关资源
    最近更新 更多