我正在研究一些用于生成随机字符串的代码。结果字符串似乎包含无效char
组合。具体来说,我发现高代理项后面没有低代理项。
谁能解释为什么会这样?我是否必须明确生成随机低代理来跟随高代理?我以为这不是必需的,因为我使用的int
是Character
。
这是测试代码,在最近的一次运行中产生了以下错误配对:
配对不良:d928 - d863 配对不良:da02 - 7bb6 配对不良:dbbc - d85c 配对不良: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;
}
}