我写了一个程序来生成随机的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��Ꙙ@
String
,而不是字节,所以用什么字节构造它是无关紧要的。 - artbristol