Reputation: 15821
I have a string, actually user put in console next string :
10 20 30 40 50
how i can parse it to int[]
?
I tried to use Integer.parseInt(String s);
and parse string with String.indexOf(char c)
but i think it's too awful solution.
Upvotes: 1
Views: 3177
Reputation: 7501
You could use a Scanner
and .nextInt()
, or you could use the .split()
command on the String to split it into an array of Strings and parse them separately.
For example:
Scanner scanner = new Scanner(yourString);
ArrayList<Integer> myInts = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
myInts.add(scanner.nextInt());
}
For the split
:
String[] intParts = yourString.split("\\s+");
ArrayList<Integer> myInts = new ArrayList<Integer>();
for (String intPart : intParts) {
myInts.add(Integer.parseInt(intPart));
}
Upvotes: 11
Reputation: 936
Split the string then parse the integers like the following function:
int[] parseInts(String s){
String[] sNums = s.split(" ");
int[] nums = new int[sNums.length];
for(int i = 0; i < sNums.length; i++){
nums[i] = Integer.parseInt(sNums[i);
}
return nums;
}
Upvotes: 0
Reputation: 26198
String split[] = string.split(" ")
is will generate an array of string then you can parse the array to int.
Upvotes: 1
Reputation: 45060
String#split()
method with the delimiter space.String[]
, parse it into an int
using Integer.parseInt()
and add them to your int[]
.Upvotes: 1