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

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

    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 values = magicallyGetListFromString(s);
            for (Integer integer : values)
            {
                System.out.println(integer);
            }
        }
    
        public static List magicallyGetListFromString(String s)
        {
            List numberList = new ArrayList(); 
            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;
        }
    }
    

提交回复
热议问题