Skip to content
Advertisement

Java: Find numbers or letters between bounds given in string

I have strings like 1-3, 11-16, a-d, C-G.

Is there a way to generate an array of all the values in between(inclusive). So for example the string a-d would return an array [‘a’,’b’,’c’,’d’] and 11-16 would return[11,12,13,14,15,16]?

Advertisement

Answer

This should work:

        String[] myString = new String[]{"1-3","11-16", "a-d","C-G"};

        for (String string: myString){
            String[] split = string.split("-");
            try {
                for (int i = Integer.parseInt(split[0]); i <= Integer.parseInt(split[1]); i++) {
                    System.out.print(i + " ");
                }
            }
            catch (NumberFormatException e){
                for (char i = split[0].charAt(0); i <= split[1].charAt(0); i++) {
                    System.out.print(i + " ");
                }
            }
            System.out.println();
        }

Here, I am only printing out the result. If you want to put the result in an array, you can create an arrayList and add the elements to that list where I am printing.

Edit: If you want to save them do this instead:

        String[] myString = new String[]{"1-3","11-16", "a-d","C-G"};

        ArrayList<ArrayList<Character>> charArray = new ArrayList<>();
        ArrayList<ArrayList<Integer>> intArray = new ArrayList<>();

        for (String string: myString){
            String[] split = string.split("-");
            try {
                ArrayList<Integer> currentArray= new ArrayList<>();
                for (int i = Integer.parseInt(split[0]); i <= Integer.parseInt(split[1]); i++) {
                    currentArray.add(i);
                }
                intArray.add(currentArray);
            }
            catch (NumberFormatException e){
                ArrayList<Character> currentArray= new ArrayList<>();
                for (char i = split[0].charAt(0); i <= split[1].charAt(0); i++) {
                    currentArray.add(i);
                }
                charArray.add(currentArray);
            }
        }

        System.out.println(charArray);
        System.out.println(intArray);
    }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement