Yehudah
Yehudah

Reputation: 65

Splitting a string separated by commas and storing the value into an int array

I have a string which I want to split by the commas (easy process):

String numbers = "1,2,3";

But, I then want to convert each element of the split string into an int that can be stored in an int array separated by commas as:

int[][] array = new int [0][];
array[0] = new int[] {1,2,3};

How can I achieve this?

Upvotes: 0

Views: 4909

Answers (5)

shmosel
shmosel

Reputation: 50716

array[0] = Arrays.stream(numbers.split(","))
        .mapToInt(Integer::parseInt)
        .toArray();

Upvotes: 0

Mehul Raheja
Mehul Raheja

Reputation: 152

    String s = "1,2,3";

    StringTokenizer st = new StringTokenizer(s,",");
    int[][] array = new int [0][];
    int i = 0;
    while(st.hasMoreElements()) {
        int n = Integer.parseInt((String) st.nextElement());
        array[0][i] = n;
        i++;
    }

This is twice as fast as String.split()

Upvotes: 0

Aleksandar Đokić
Aleksandar Đokić

Reputation: 2333

You dont need 2D array, you can use simple array. It will be enough to store this data. Just split it by ',' and then iterate through that array,parse everything int and add that parsed values to new array.

  String numbers = "1,2,3,4,5";
        String[] splitedArr= numbers.split(",");
        int[] arr = new int[splitedArr.length];
        for(int i = 0; i < splitedArr.length; i++) {
            arr[i] = Integer.parseInt(splitedArr[i]);
        }
       System.out.println(Arrays.toString(arr)); 

Upvotes: 0

Chris Gong
Chris Gong

Reputation: 8229

The 2D array is unnecessary. All you need to do is splice the commas out of the string using the split method. Then convert each element in the resulting array into an int. Here's what it should look like,

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

Upvotes: 2

Yeongjun Kim
Yeongjun Kim

Reputation: 749

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

Upvotes: 0

Related Questions