-
October 6th, 2021, 11:26 AM
#1
A Fast method of Converting String to int array in Java?
Hi,
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?
Last edited by codighack; October 6th, 2021 at 01:12 PM.
-
October 6th, 2021, 01:06 PM
#2
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.
-
November 16th, 2021, 09:55 AM
#3
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
Norm
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|