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
public static void main(String[] args) {
String str = "1,2,5-9,11,12,19-21";
String[] val = str.split(",");
List<Integer> l = new ArrayList<Integer>();
for (String s : val) {
if (s.contains("-")) {
String[] strVal = s.split("-");
int startVal = Integer.parseInt(strVal[0]);
int endVal = Integer.parseInt(strVal[1]);
for (int i = startVal; i <= endVal; i++) {
l.add(i);
}
} else {
l.add(Integer.parseInt(s));
}
}
for (int j : l) {
System.out.println(j);
}
}
O/P : 1 2 5 6 7 8 9 11 12 19 20 21
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));
}
}
Magic you are looking at
public static List<Integer> magicallyGetListFromString(String s){
String[] str=s.split(",");
List<Integer> result=new ArrayList<Integer>();
for(String i:str){
if(i.contains("-")){
String[] ss=i.split("-");
int lower= Integer.parseInt(ss[0]);
int upper= Integer.parseInt(ss[1]);
for(int j=lower;j<=upper;j++){
result.add(j);
}
}else {
result.add(Integer.parseInt(i));
}
}
return result;
}
Result:
[1, 2, 5, 6, 7, 8, 9, 11, 12]
This should work:
public class StringMagic
{
public static void main(String[] args)
{
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);
for (Integer integer : values)
{
System.out.println(integer);
}
}
public static List<Integer> magicallyGetListFromString(String s)
{
List<Integer> numberList = new ArrayList<Integer>();
String[] numbers = s.split(",");
for (String string : numbers)
{
if (!string.contains("-"))
{
numberList.add(Integer.parseInt(string));
}
else
{
String[] limits = string.split("-");
int bottomLimit = Integer.parseInt(limits[0]);
int upperLimit = Integer.parseInt(limits[1]);
for(int i = bottomLimit; i <= upperLimit; i++)
{
numberList.add(i);
}
}
}
return numberList;
}
}