我正在编写一些用于生成随机字符串的代码。结果字符串似乎包含无效的char
组合。具体而言,我发现很高的代理人没有跟随低代理人。如何生成包含补充字符的随机Unicode字符串?
任何人都可以解释为什么发生这种情况?我是否必须明确地生成一个随机低代理来跟随高代理?我以为这是不需要的,因为我使用Character
类的int
变体。
这里的测试代码,这在最近的运行产生以下不好的配对:
Bad pairing: d928 - d863 Bad pairing: da02 - 7bb6 Bad pairing: dbbc - d85c Bad pairing: dbc6 - d85c
public static void main(String[] args) {
Random r = new Random();
StringBuilder builder = new StringBuilder();
int count = 500;
while (count > 0) {
int codePoint = r.nextInt(Character.MAX_CODE_POINT + 1);
if (!Character.isDefined(codePoint)
|| Character.getType(codePoint) == Character.PRIVATE_USE) {
continue;
}
builder.appendCodePoint(codePoint);
count--;
}
String result = builder.toString();
// Test the result
char lastChar = 0;
for (int i = 0; i < result.length(); i++) {
char c = result.charAt(i);
if (Character.isHighSurrogate(lastChar) && !Character.isLowSurrogate(c)) {
System.out.println(String.format("Bad pairing: %s - %s",
Integer.toHexString(lastChar), Integer.toHexString(c)));
}
lastChar = c;
}
}
Character.isDefined的代理人返回true。 – VGR