gpt4 book ai didi

java - appendCodePoint() 和 codePointAt()

转载 作者:行者123 更新时间:2023-11-30 06:16:16 24 4
gpt4 key购买 nike

为什么下面的程序打印错误,我必须做哪些更改才能使其打印正确?

public class Main {

static int[] codePoints(String s) {
int n = s.length();
int[] temp = new int[n];
for (int i = 0; i < n; i++)
temp[i] = s.codePointAt(i);
return temp;
}

static String construct(int[] codePoints) {
StringBuilder sb = new StringBuilder();
for (int i : codePoints)
sb.appendCodePoint(i);
return sb.toString();
}

public static void main(String[] args) {
StringBuilder sb = new StringBuilder("The symbol ");
sb.appendCodePoint(Character.MAX_VALUE + 1);
sb.append(" is not in the Basic Multilingual Plane.");
String s = sb.toString();
System.out.println(s.equals(construct(codePoints(s))));
}
}

最佳答案

问题出在这里:

static int[] codePoints(String s) {
int n = s.length();
int[] temp = new int[n];
for (int i = 0; i < n; i++)
temp[i] = s.codePointAt(i); // <-- HERE
return temp;
}

BMP 之外的代码点是两个 char 宽,而不是一个(参见Character.toChars());如果你遇到这样的代码点,你需要检查并推进你的索引:

static int[] codePoints(final String s)
{
final int len = s.length();
final int[] ret = new int[s.codePointCount(0, len)];
int nrCodePoints = 0;
int codePoint;
int index;
for (index = 0; index < len; index++) {
codePoint = s.codePointAt(index);
ret[nrCodePoints++] = codePoint;
if (codePoint > Character.MAX_VALUE)
index++;
}
return ret;
}

关于java - appendCodePoint() 和 codePointAt(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27597293/

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