简体   繁体   English

快速将String转换为Java中的int数组

[英]Convert String to int array in Java the fast way

does anyone know a faster way to convert string to int array? 有谁知道将字符串转换为int数组的更快方法?

Java V7 Java V7

The format given is " 4 343 234 -24 " and so on. 给定的格式为“ 4 343 234 -24 ”,依此类推。 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). 当您想用单个字符(在您的情况下为空格)分割时,使用String.split()是最有效的方法。

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. 如果您使用的是Java8或更高版本,则可以通过编写以下单行代码来获得预期的输出。

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. 用模式\\\\s+分隔输入将处理一个或多个空格字符,不仅数字之间出现空格,而且还包括空格。

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

The mapToInt method returns an IntStream which provides the toArray method. mapToInt方法返回提供toArray方法的IntStream This method returns an array containing the elements of the IntStream . 此方法返回一个包含IntStream元素的IntStream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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