用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]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP