1

does anyone know a faster way to convert string to int array?

Java V7

The format given is "4 343 234 -24" and so on. Spaces between the numbers, amount of numbers is known beforhand just as is the range within the numbers are

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);
kaiya
  • 271
  • 1
  • 3
  • 16
  • 3
    If it is working already better you post it on codereview.stackexchange.com – Suresh Atta Dec 21 '17 at 12:41
  • try splitting the input string into the component numbers then converting each of those to a long/int as appropriate – AdamPillingTech Dec 21 '17 at 12:41
  • Just use `String#split` that will split your string depending of a delimiter (use " " here), and you get an array of all different numbers. – Turtle Dec 21 '17 at 12:42
  • 2
    I'm voting to close this question as off-topic because questions asking to review working code belong on codereview.stackexchange.com – GhostCat Dec 21 '17 at 12:48

3 Answers3

1

Using String.split() is by far the most efficient when you want to split by a single character (a space, in your case).

If you are aiming for maximal efficiency when splitting by spaces, then this would be a good solution:

List<Integer> res = new ArrayList<>();
Arrays.asList(kraft.split(" ")).forEach(s->res.add(Integer.parseInt(s)));
Integer[] result = res.toArray(new Integer[0]);

And this works for any number of numbers.

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
0

if You are using Java8 or higher version then you can get your expected output by writing this single line of code.

String str= "4 343 234 -24";

int[] intArr=Stream.of(str.split(" ")).mapToInt(Integer::parseInt).toArray();

System.out.println(Arrays.toString(intArr));
0

Splitting the input with the pattern \\s+ would handle one or more white-space characters, not only spaces, appearing between the numbers.

Stream.of(input.split("\\s+")).mapToInt(Integer::parseInt).toArray();

The mapToInt method returns an IntStream which provides the toArray method. This method returns an array containing the elements of the IntStream.

senjin.hajrulahovic
  • 2,961
  • 2
  • 17
  • 32