我写了一个程序来生成一个随机的 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��Ꙙ@