A Fast method of Converting String to int array in Java?
Hi, :wave:
I am using Java V7. Is there a fast way to convert String to int array in Java?
The Given format is "4 343 234 -24" and so on. Spaces between the numbers, amount of numbers is known beforehand just as is the range within the numbers are
Code:
long[] array = new long[length];
for (int i = 0; i < length - 1; i++) {
array[i] = Integer.parseInt(n.substring(0, n.indexOf(' ')));
n = n.substring(n.substring(0, n.indexOf(' ')).length() + 1);
}
array[length - 1] = Integer.parseInt(n);
Edit: I was going through this resource, could you guys help me with a more relevant resource pertaining to my query?
Re: A Fast method of Converting String to int array in Java?
Using String.split() is by far the most efficient when you want to split by a single character (a space, in your case).
This would be a good solution if you are aiming for maximum efficiency when splitting by spaces.
Code:
List<Integer> res = new ArrayList<>();
Arrays.asList(kraft.split(" ")).forEach(s->res.add(Integer.parseInt(s)));
Integer[] result = res.toArray(new Integer[0]);
This works for any number of numbers.
Re: A Fast method of Converting String to int array in Java?
Use split to create a String array with the separated numbers (as Strings)
Create in int array of the same size
loop through the String array using Integer.parseInt to convert each String and assign the int values to the int array