how to convert an integer string separated by space into an array in JAVA
For java 8+ you can use this way:
final Integer[] ints = Arrays.stream(numbers.split(" "))
.map(Integer::parseInt)
.toArray(Integer[]::new);
or, if you need primitive ints, you can use this:
final int[] ints = Arrays.stream(numbers.split(" "))
.mapToInt(Integer::parseInt)
.toArray();
You are forgetting about
- resetting
temp
to empty string after you parse it to create place for new digits that at the end of your string will be no space, so
if (numbers.charAt(i) == ' ') { ary[j] = Integer.parseInt(temp); j++; }
will not be invoked, which means you need invoke
ary[j] = Integer.parseInt(temp);
once again after your loop
But simpler way would be just using split(" ")
to create temporary array of tokens and then parse each token to int
like
String numbers = "12 1 890 65";
String[] tokens = numbers.split(" ");
int[] ary = new int[tokens.length];
int i = 0;
for (String token : tokens){
ary[i++] = Integer.parseInt(token);
}
which can also be shortened with streams added in Java 8:
String numbers = "12 1 890 65";
int[] array = Stream.of(numbers.split(" "))
.mapToInt(token -> Integer.parseInt(token))
.toArray();
Other approach could be using Scanner
and its nextInt()
method to return all integers from your input. With assumption that you already know the size of needed array you can simply use
String numbers = "12 1 890 65";
int[] ary = new int[4];
int i = 0;
Scanner sc = new Scanner(numbers);
while(sc.hasNextInt()){
ary[i++] = sc.nextInt();
}