问题
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?
回答1:
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]);
}
回答2:
String[] strArr = numbers.split(",");
int[][] array = new int[1][];
for(int i = 0; i < strArr.length; i++) {
array[0][i] = Integer.parseInt(strArr[i]);
}
回答3:
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));
回答4:
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()
回答5:
array[0] = Arrays.stream(numbers.split(","))
.mapToInt(Integer::parseInt)
.toArray();
来源:https://stackoverflow.com/questions/38908568/splitting-a-string-separated-by-commas-and-storing-the-value-into-an-int-array