共計 601 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
要將一個字符串放入數(shù)組中,可以按照以下步驟進行操作:
- 創(chuàng)建一個新的數(shù)組,數(shù)組的大小為字符串的長度。
- 使用
toCharArray()方法將字符串轉(zhuǎn)換為字符數(shù)組。 - 使用
System.arraycopy()方法將字符數(shù)組復(fù)制到新的數(shù)組中。
以下是一個示例代碼:
public class StringToArray {public static void main(String[] args) {String str = "Hello, World!";
char[] charArray = str.toCharArray();
// 創(chuàng)建一個新的數(shù)組,大小為字符串的長度
char[] newArray = new char[str.length()];
// 將字符數(shù)組復(fù)制到新的數(shù)組中
System.arraycopy(charArray, 0, newArray, 0, str.length());
System.out.println(" 原始字符串: " + str);
System.out.println(" 新的數(shù)組: " + Arrays.toString(newArray));
}
}
輸出結(jié)果:
原始字符串: Hello, World!
新的數(shù)組: [H, e, l, l, o, ,, , W, o, r, l, d, !]
在上面的示例中,我們首先將字符串轉(zhuǎn)換為字符數(shù)組,然后創(chuàng)建一個新的數(shù)組,最后使用 System.arraycopy() 方法將字符數(shù)組復(fù)制到新的數(shù)組中。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完