我写了一个程序来生成一个随机的utf-8字符串,但是有些混乱.
我不知道我的代码是否错误或某些字符不可见,如何去除这些混乱的字符(但我想保留中文,韩文,日文,符号等)?
有代码:
private byte randomByteInRange(int min, int max) {
return (byte) (min + rand.nextInt(max - min));
}
private String randomUtf8String(int length) throws UnsupportedEncodingException {
int j = 0;
byte[] bytes = new byte[6 * length];
for (int i = 0; i < length; ++i) {
int mod = i % 3;
if (0 == mod) { // 0xxxxxxx, visible char: 0x20 ~ 0x80
bytes[j++] = randomByteInRange(0x20, 0x80);
}
if (1 == mod) { // 110xxxxx 10xxxxxx
bytes[j++] = randomByteInRange(0xc0, 0xdf);
bytes[j++] = randomByteInRange(0x80, 0xbf);
}
if (2 == mod) { // 1110xxxx 10xxxxxx 10xxxxxx
bytes[j++] = randomByteInRange(0xe0, 0xef);
bytes[j++] = randomByteInRange(0x80, 0xbf);
bytes[j++] = randomByteInRange(0x80, 0xbf);
}
}
return new String(bytes, 0, j, "UTF-8").replaceAll("\\p{C}+", "");
}
有我的输出:
kѷ㱾U拌w��Ꙙ@
解决方法:
我可以想到以这种方式生成随机字符串的几个问题:
>未分配范围,保留范围和专用区域
>控制字符
>组合仅在某些其他代码点之后才有意义的标记(例如diacritics)
>字体支持(例如,您的设备会显示Ogham script吗?)
为了实现有意义的随机字符串生成器,您的代码将需要应用一些过滤器和自然语言试探法.
假设这是用于本地化烟雾测试…
作为一种替代方法,请考虑使用目标语言中的常用短语,日期等,或使用目标语言文本源中生成的某种马尔可夫链.自动翻译软件还可以为您合理地表示目标字符串.
标签:utf-8,java
来源: https://codeday.me/bug/20191201/2077287.html