[英]String Splitting in java
I am trying to split the following strings: 我正在尝试拆分以下字符串:
1396*43
23*
56*
122*37*87
All of these are stored in an array. 所有这些都存储在一个数组中。 Following is a part of my code:
以下是我的代码的一部分:
for(int i=0;i<array.length;i++)
{
String[] tokens = array[i].split("\\*");
System.out.println(tokens[1]);
}
It only prints "43" stored in first index and not "37" stored in last index. 它仅打印存储在第一个索引中的“ 43”,而不打印存储在最后一个索引中的“ 37”。
You are getting an IndexOutOfBoundsException cause you are trying to get tokens[1] on the second line (the length of tokens there is 1). 您正在获取IndexOutOfBoundsException,因为您尝试在第二行获取令牌[1](令牌的长度为1)。
Change your code this way: 通过以下方式更改代码:
for(int i=0;i<array.length;i++) {
String[] tokens = array[i].split("\\*");
if (tokens.length > 1) {
System.out.println(tokens[1]);
}
}
When using spilt, make sure have a token value in the first place. 使用spilt时,请确保首先具有令牌值。 Even not, handle it.
即使没有,也要处理。
public class TestMain {
public static void main(String[] args) {
String array[]=new String[200];
array[0]="1396*43";
array[1]="23*";
array[2]="56*";
array[3]="122*37*87";
for(int i=0;i<array.length;i++)
{
if(null!=array && null!= array[i] && null!=array[i].split("\\*")){
String[] tokens = array[i].split("\\*");
if (tokens.length > 1) {
System.out.println(tokens[1]);
}
}
}
}
}
Solution with Java8 and streams: Java8和流的解决方案:
String[] words = {"1396*43",
"23*",
"56*",
"122*37*87"};
List<String> numbers = Arrays.stream(words)
.map(word -> word.split("\\*"))
.flatMap(Arrays::stream)
.collect(Collectors.toList());
numbers.forEach(System.out::println);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.