Java 程式,如何將字串中的字元作為位元組陣列獲取


要將字串中的字元作為位元組陣列獲取,請使用 getBytes() 方法。

假設我們有以下字串。

String str = "Demo Text!";

將它轉換為位元組陣列。

byte[] arr = str.getBytes();

示例

 現場演示

public class Demo {
   public static void main(String[] args) {
      String str = "Demo Text!";
      // getting as an array of bytes
      byte[] arr = str.getBytes();
      // displaying each character as a Byte value
      for(byte res: arr) {
         System.out.println(res);
      }
   }
}

輸出

68
101
109
111
32
84
101
120
116
33

更新於: 26-Jun-2020

277 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告