Convert the input Strings into a Series

Viewed 83

In the following program, i am trying to check if the consecutive strings in the input array are in a sequence and if so they should be represented as a range as you can see below. I am able to convert two consecutive strings as a range but i can't figure out how to check and convert more than two consecutive strings in a range.

    import java.util.*;
    public class HelloWorld{
    public static void main(String []args){
    System.out.println("Hello World");
    String input = "abc0001, abc0002, abc002, efg00113, efg00114, efg00115, rtasdf1";
    String[] result = input.split(", ");
    List<String> output = new ArrayList<String>();
    for(int i = 0; i < result.length - 1; ++i){
        String[] first = result[i].split("(?<=\\D)(?=\\d)");
        int digits1 = Integer.parseInt(first[1]);
        String[] second = result[i + 1].split("(?<=\\D)(?=\\d)");
        int digits2 = Integer.parseInt(second[1]);
        if(second[0].equals(first[0]) && (second[1].length() == first[1].length()) && ((digits2 - digits1) == 1)) {
            result[i] = result[i] + "-" + result[i + 1];
            output.add(result[i]);
            ++i;
        }
        else {
            output.add(result[i]);
        }
    }
    String [] out = output.toArray(new String[output.size()]);
    for(String a : out)
        System.out.println(a);

    //Arrays.sort(result);
    //for(String a : result)
    //    System.out.println(a);

    }
    }

Output :

    Hello World                                                                                                                                           
    abc0001-abc0002                                                                                                                                           
    abc002                                                                                                                                                    
    efg00113-efg00114                                                                                                                                        
    efg00115  

The last output should be efg00113-efg00115 instead of efg00113-efg00114 and efg00115 separately.

2 Answers
Related