我已經嘗試了很多帶有隨機字符的字符串,除了空字符串「」,它們的.getBytes()字節數組似乎永遠不會包含任何0值(如{123,-23,54,0,-92})。String.getBytes()的結果是否包含零?
它的.getBytes()字節數組總是不包含除了空字符串之外的所有nero嗎?
編輯:以前的測試代碼如下。現在我瞭解到,在Java 8中,如果字符串由(char)random.nextInt(65535)+ 1組成,結果似乎總是「不包含0」如果字符串包含(char)0,則「包含0」。
private static String randomString(int length){
Random random = new Random();
char[] chars = new char[length];
for (int i = 0; i < length; i++){
int integer = random.nextInt(65535) + 1;
chars[i] = (char) (integer);
}
return new String(chars);
}
public static void main(String[] args) throws Exception {
for (int i = 1; i < 100000; i++){
String s1 = randomString(10);
byte[] bytes = s1.getBytes();
for (byte b : bytes) {
if (b == 0){
System.out.println("contains 0");
System.exit(0);
}
}
}
System.out.println("contains no 0");
}
你能提供你已經嘗試和代碼以及絃樂。只提供最少和特定的代碼。 – YoungHobbit
請注意,在幾個[標準字符集](https://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html)中,空字符串'「」'不*編碼轉換爲帶有'0'元素的字節數組。 ASCII,UTF-8和ISO_8859_1都將空字符串表示爲空數組。如果你看到''''編碼爲'{0}',那麼你的系統正在使用其他默認字符集,並且你不應該期望你的結果是典型的。 – dimo414
對不起,我沒有仔細檢查。空字符串對我來說也是一個空數組。 – Tom