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

后端 未结 4 1288
野趣味
野趣味 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:36

    Magic you are looking at

    public static List magicallyGetListFromString(String s){
       String[] str=s.split(",");
       List result=new ArrayList();
       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]
    

提交回复
热议问题