用Java將字串轉換為字元陣列有多少種方法?


您可以透過將字串的每個元素複製到陣列中,或者使用 toCharArray() 方法將字串轉換為字元陣列。

複製每個元素

  • 獲取要轉換的字串。

  • 建立一個與字串長度相同的空字元陣列。

  • String 類的 **charAt()** 方法返回特定位置的字元。使用此方法將字串的每個字元複製到陣列中。

示例

 線上演示

import java.util.Arrays;
import java.util.Scanner;
public class StringToCharArray {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String value: ");
      String str = sc.next();
      //Creating an empty array with the length of the String
      char chArray[] = new char[str.length()];
      //Copying each element of the String to the array
      for(int i=0; i<str.length(); i++) {
         chArray[i] = str.charAt(i);
      }
      System.out.println("Contents of the character array: ");
      System.out.println(Arrays.toString(chArray));
   }
}

輸出

Enter a String value:
Tutorialspoint
Contents of the String array:
[T, u, t, o, r, i, a, l, s, p, o, i, n, t]

使用 toCharArray() 方法

String 類的 **toCharArray()** 方法將當前字串轉換為字元陣列並返回它。因此,要使用此方法將字串轉換為字元陣列:

  • 獲取要轉換的字串。

  • 建立一個與字串長度相同的空字元陣列。

  • 使用 toCharArray() 方法將字串轉換為字元陣列,並將其儲存在上面建立的空陣列中。

示例

 線上演示

import java.util.Arrays;
import java.util.Scanner;
public class ToCharArrayExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String value: ");
      String str = sc.next();
      //Creating an empty array with the length of the String
      char chArray[] = str.toCharArray();
      System.out.println("Contents of the character array: ");
      System.out.println(Arrays.toString(chArray));
   }
}

輸出

Enter a String value:
Tutorialspoint
Contents of the character array:
[T, u, t, o, r, i, a, l, s, p, o, i, n, t]

更新於:2019年10月10日

225 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.