如何轉換爲字符串,如:如何將字符串數組轉換爲int數組?
"114 214 219"
成一個int數組,所以我有這樣的事情存儲在我的int數組:
int[] couseNumbers = int[3];
for(int i = 0; i < 3; i++){
courseNumbers[i] = Integer.parseInt(/*get int in the string array*/);
}
如何轉換爲字符串,如:如何將字符串數組轉換爲int數組?
"114 214 219"
成一個int數組,所以我有這樣的事情存儲在我的int數組:
int[] couseNumbers = int[3];
for(int i = 0; i < 3; i++){
courseNumbers[i] = Integer.parseInt(/*get int in the string array*/);
}
首先將字符串拆分爲數組。
String[] stringArray = "114 214 219".split(" ");
然後在循環中,您可以訪問陣列:
courseNumbers[i] = Integer.parseInt(stringArray[i])
非常感謝! –
如果它幫助你,請將我的答案標記爲解答;) – Markus
使用Java 8流。
List<Integer> courseNumbers = Arrays.stream("1123 213 23"
.split(" ")).map(x-> Integer.parseInt(x))
.collect(Collectors.toList());
謝謝,但它會更好的數組。 –
試試這個
String s = "1 2 3";
String array[] = s.split(" "); //Splits the Array by spaces
int a[] = new int[array.length]; //Makes new int array
for(int i=0;i<a.length;i++){
a[i] = Integer.parseInt(array[i]); //Converts String to int
}
感謝您的幫助! –
回答上述由愛德華丹尼斯不會爲字符串工作不能轉化爲直接詮釋。你可以做這樣的事情。
public static void main(String []args){
String s = "114 214 219";
String [] courseNumbers = s.split(" ");
Integer [] intArray = new Integer[courseNumbers.length];
for(int i= 0; i < courseNumbers.length; i++){
intArray[i] = Integer.parseInt(courseNumbers[i]);
}
}
非常感謝! –
我不明白你的問題是什麼?你擁有的代碼應該工作得很好。 – Jdman1699
那麼,除了'couseNumbers'和'courseNumbers'是不同的名字...... –