简体   繁体   中英

Convert String to int array in Java the fast way

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);

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.

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));

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM