是否有一种简单的方法将以下字符串解析为整数列表:
String s = "1,2,5-9,11,12"
// expected values list: [1,2,5,6,7,8,9,11,12]
List<Integer> values = magicallyGetListFromString(s);
我想知道是否有一种简单的方法可以做到这一点,而不是自己编写。
最佳答案
List<Integer> out=new ArrayList<Integer>();
String numbers[]=s.split(",");
for(String part:numbers){
if(part.contains("-"){
int a=Integer.parseInt(part.split("-")[0]);
int b=Integer.parseInt(part.split("-")[1]);
while(a<=b){
out.add(a++);
}
}else{
out.add(Integer.parseInt(part));
}
}
关于java - 使用逗号和 "-"将字符串拆分为整数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24630698/