Splitting String to list of Integers with comma and “-”

后端 未结 4 1290
野趣味
野趣味 2021-01-27 15:57

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

        
4条回答
  •  长情又很酷
    2021-01-27 16:33

    List out=new ArrayList();
    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));
        }
    }
    

提交回复
热议问题