![](/img/trans.png)
[英]splitting string by comma and space in order to store them into 2 different array
[英]Splitting the string and store it in an array
我希望將以下字符串存儲到數組中,但會引發ArrayOutOfBound異常。
public static void main(String[] args) {
// TODO Auto-generated method stub
char[] arr = {};
String str = "Hello My Name is Ivkaran";
for (int i = 0;i < str.length(); i++){
System.out.println(str.charAt(i));
arr[i] = str.charAt(i);
}
}
您已在此行中聲明了一個長度為0的數組:
char[] arr = {};
要將任何內容分配給該數組,必須將其初始化為一些非零的大小。 在這里,看起來您需要它與字符串大小相同。
String str = "Hello My Name is Ivkaran";
char[] arr = new char[str.length()];
您也可以只調用String
上的toCharArray()
以獲得一個char[]
,其內容已復制到其中。
char[] arr = str.toCharArray();
數組在Java中不是動態的。 使用arraylist或創建帶有尺寸的數組,如下所示:
char[] arr = new char[str.length()]
還將這條線移到
String str = "Hello My Name is Ivkaran";
然后按原樣繼續。
只要這樣做:
String str = "Hello My Name is Ivkaran";
char[] arr = str.toCharArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.