使用逗号和“-"将字符串拆分为整数列表 [英] Splitting String to list of Integers with comma and "-"
本文介绍了使用逗号和“-"将字符串拆分为整数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种简单的方法可以将以下字符串解析为整数列表:
Is there a simple way to parse the following String to List of Integers:
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);
我想知道是否有一种简单的方法,而不是自己编写.
I was wondering if there is a simple way to do it, rather than writing it by myself.
推荐答案
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));
}
}
这篇关于使用逗号和“-"将字符串拆分为整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文