Java 程式,從字串物件建立字元陣列


在 Java 中使用 toCharArray() 方法從字串物件建立字元陣列。以下是我們的字串。

String str = "This is it!";

現在,讓我們從以上字串建立字元陣列。

char[] strArr = str.toCharArray();

示例

 線上演示

public class Demo {
   public static void main(String[] args) {
      String str = "This is it!";
      char[] strArr = str.toCharArray();
      for(char res: strArr) {
         System.out.println(res);
      }
   }
}

輸出

T
h
i
s

i
s

i
t
!

讓我們看另一個示例,其中我們使用 new 運算子建立字串。

示例

 線上演示

public class Demo {
   public static void main(String[] args) {
      String str = new String("This is another string!");
      char[] strArr = str.toCharArray();
      for(char res: strArr) {
         System.out.println(res);
      }
   }
}

輸出

T
h
i
s

i
s

a
n
o
t
h
e
r

s
t
r
i
n
g
!

更新於:2020 年 6 月 26 日

242 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.