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

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

    public static void main(String[] args) {
        String str = "1,2,5-9,11,12,19-21";
        String[] val = str.split(",");
        List l = new ArrayList();
        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

提交回复
热议问题