作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写一些用于生成随机字符串的代码。生成的字符串似乎包含无效的 char
组合。具体来说,我发现高代理项后面没有低代理项。
谁能解释一下为什么会发生这种情况?我是否必须显式生成随机低代理才能跟随高代理?我认为这不是必需的,因为我使用的是 Character
类的 int
变体。
这是测试代码,在最近的运行中产生了以下错误的配对:
Bad pairing: d928 - d863Bad pairing: da02 - 7bb6Bad pairing: dbbc - d85cBad 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;
}
}
最佳答案
可以随机生成高或低的代理。如果这导致低代理项,或者高代理项后面没有低代理项,则生成的字符串无效。解决方案是简单地排除所有代理:
if (!Character.isDefined(codePoint)
|| (codePoint <= Character.MAX_CHAR && Character.isSurrogate((char)codePoint))
|| Character.getType(codePoint) == Character.PRIVATE_USE) {
continue;
}
或者,它应该只查看从 getType
返回的类型:
int type = Character.getType(codePoint);
if (type == Character.PRIVATE_USE ||
type == Character.SURROGATE ||
type == Character.UNASSIGNED)
continue;
(从技术上讲,您还可以允许随机生成高代理并添加另一个随机低代理,但这只会创建其他随机代码点 >= 0x10000,而这些代码点可能是未定义的或供私有(private)使用。)
关于java - 如何生成包含增补字符的随机 Unicode 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41109905/
我是一名优秀的程序员,十分优秀!