问题遇到的现象和发生背景
如将字符串"A1B2C3D4E5F6G7H8",通过split(“[A-Z]”)处理后,得出的字符串数组,想将此数组转成Int类型数组,但由于存在空串导致出现NumberFormatException。搜索了一些处理方案,如split("[A-Z]",StringSplitOptions.RemoveEmptyEntries),但是我这并没有这个StringSplitOptions,所以调用不了。
想知道除了循环之外,有没有其他的方式来解决这个问题?
问题相关代码,请勿粘贴截图
String s = "A1B2C3D4E5F6G7H8";
// System.out.println(s);
// String[] split = s.split("\\D");
// System.out.println(split.toString());
// int[] ints = Arrays.stream(s.split("\\D")).mapToInt(i -> Integer.parseInt(i)).toArray();
// String[] sarr = s.split("\\d");
// System.out.println(ints);
// Arrays.stream(sarr).forEach(System.out::print);
// String[] st = new String[]{"a","b","c","d"};
// System.out.println();
System.out.println(s);
String[] sp = s.split("[A-Z]");
Arrays.stream(sp).forEach(System.out::println);
// System.out.println(sp.length);
int[] intarr = new int[]{};
for (int is = 0;is < sp.length;is++){
intarr[is] = Integer.valueOf(sp[is]);
}
// Arrays.stream(sp).forEach(System.out::print);
Arrays.stream(intarr).forEach(System.out::println);
运行结果及报错内容
A1B2C3D4E5F6G7H8
1
2
3
4
5
6
7
8
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at sevtnthForBookTest.subTest.main(subTest.java:31)
我的解答思路和尝试过的方法
我想要达到的结果
数组类型由String 转变为Int