How to put a string into an array in Java?
To place a string into an array, you can follow these steps:
- Create a new array with a length equal to the size of the string.
- Convert to an array of characters.
- Copy the elements of an array into another array using System.arraycopy().
Here is an example code:
public class StringToArray {
public static void main(String[] args) {
String str = "Hello, World!";
char[] charArray = str.toCharArray();
// 创建一个新的数组,大小为字符串的长度
char[] newArray = new char[str.length()];
// 将字符数组复制到新的数组中
System.arraycopy(charArray, 0, newArray, 0, str.length());
System.out.println("原始字符串: " + str);
System.out.println("新的数组: " + Arrays.toString(newArray));
}
}
Output result:
原始字符串: Hello, World!
新的数组: [H, e, l, l, o, ,, , W, o, r, l, d, !]
In the example above, we first convert the string into a character array, then create a new array, and finally copy the character array into the new array using the System.arraycopy() method.