2016-03-03 83 views
-2
//convert the comma separated numeric string into the array of int. 
    public class HelloWorld 
    { 
     public static void main(String[] args) 
     { 
     // line is the input which have the comma separated number 
     String line = "1,2,3,1,2,2,1,2,3,"; 
     // 1 > split 
     String[] inputNumber = line.split(","); 
     // 1.1 > declare int array 
     int number []= new int[10]; 
     // 2 > convert the String into int and save it in int array. 
     for(int i=0; i<inputNumber.length;i++){ 
       number[i]=Integer.parseInt(inputNumber[i]); 
     } 
    } 
} 

這是它們的更好的解決方案嗎?請提出建議,或者這是做到這一點的唯一最佳解決方案。如何將數字逗號分隔的字符串轉換爲int數組

這個問題的主要目的是找到最好的解決方案。

+0

注:這個問題已經被[交叉張貼在代碼審查(http://codereview.stackexchange.com/q/121756/9357)。 (沒關係,但是請向其他用戶聲明交叉帖子。) –

回答

1

的Java 8流提供了一個很好的和乾淨的解決方案:

String line = "1,2,3,1,2,2,1,2,3,"; 
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray(); 

編輯:既然你問了Java 7的 - 你做什麼已經是相當不錯的,我改變只是一個細節。您應該使用inputNumber.length初始化陣列,以便在輸入String更改時您的代碼不會中斷。

編輯2:我也改變了命名的位,使代碼更清晰。

String line = "1,2,3,1,2,2,1,2,3,"; 
String[] tokens = line.split(","); 
int[] numbers = new int[tokens.length]; 
for (int i = 0; i < tokens.length; i++) { 
    numbers[i] = Integer.parseInt(tokens[i]); 
} 
+0

謝謝我沒有關於java 8,任何與java 7相關的解決方案。 –

+0

@PrabhatYadav我編輯了我的解決方案,但是你已經非常瞭解最好你可以在Java 7中做到 – MartinS

0

通過在Java 7中這樣做,你可以先拿到String陣列,然後將其轉換爲int陣列:

String[] tokens = line.split(","); 
int[] nums = new int[tokens.length]; 

for(int x=0; x<tokens.length; x++) 
    nums[x] = Integer.parseInt(tokens[x]); 
+0

嗯是一個頗具創新性的解決方案 – shmosel

1

既然你不喜歡的Java 8,這裏是最好的™使用一些番石榴公用事業解決方案:

int[] numbers = Ints.toArray(
     Lists.transform(
       Splitter.on(',') 
         .omitEmptyStrings() 
         .splitToList("1,2,3,1,2,2,1,2,3,"), 
       Ints.stringConverter())); 
相關問題