实际Java中是否存在Processing和Eclipse中的拆分功能?
.split() 函数是否存在?当我输入:
public class Main {
public static void main(String[] args) {
String numbers = "1, 2, 3, 4, 5";
int[] numbers2 = (int[]) numbers.split(", ");
System.out.println(numbers2);
}
}
它说:
Main.java:4: error: incompatible types: String[] cannot be converted to int[]
int[] numbers2 = (int[]) numbers.split(", ");
^
1 error
回答
numbers.split(", ")返回一个String数组。您可以使用以下内容将String数组映射到int数组。
int[] numbers2 = Arrays.stream(numbers.split(", ")).mapToInt(Integer::parseInt).toArray();
- Using Pattern.splitAsStream would avoid creating the intermediate string array. `Pattern.compile(", *").splitAsStream(numbers).mapToInt(Integer::parseInt).toArray();`
- note the spaces in the input. Better would be `split("s*,s*")` or the method trim somewhere in there