Reputation: 711
Say you have a string:
String numbers = "123 11 4392034 2";
and you want to retrieve each integer in the string (separated by spaces). What is the best way to go about doing this?
Upvotes: 1
Views: 147
Reputation: 319
String[] tokens = "123 234".split("\\s")
for(String token : tokens){
println Integer.parseInt(token)
}
Links:
Notes
Upvotes: 0
Reputation: 5055
String numbers = "123 11 4392034 2";
String [] num = numbers.split(" ");
Then use this method to retrive the array of integers:
public int[] getIntegerArray(String[] numbers) throws NumberFormatException {
if (numbers!= null) {
int intarray[] = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intarray[i] = Integer.parseInt(numbers[i]);
}
return intarray;
}
return null;
}
Upvotes: 2
Reputation: 240870
split()
by space and Integer.parseInt()
on each array element
Upvotes: 6