I am having a String like this "5006,3030,8080-8083".
I want each element separately from the String:
5006
3030
8080
8081
8082
8083
Here's my code:
int i=0,j=0;
String delim = "[,]";
String hyphon = "[-]";
String example = "5006,3030,8080-8083";
String p[] = example.split(delim);
int len = p.length;
for(i=0;i<len;i++) {
    String ps[]=p[i].split(hyphon);
    if(ps.length>1) {
        int start =  Integer.parseInt(ps[0]);
        int finish = Integer.parseInt(ps[1]);
        int diff = finish-start+1;
        for(j=0;j<diff;j++) {
            System.out.println(start+j);
        }
    } else if(ps.length==1) {
        System.out.println(ps[0]);
    }
}
Is there any better solution or any class that simplifies my code?
I also want the numbers in a ascending order.
Try this code :
public static void main(String[] args) {
 String input = "5006,3030,8080-8083";
 List<Integer> list = new ArrayList<Integer>();
 String[] numbers = input.split(",");
 for (String s : numbers) {
    if (s.contains("-")) {
      String[] range = s.split("-");
      int from = Integer.parseInt(range[0]);
      int to = Integer.parseInt(range[1]);
      for (int i = from; i <= to; i++) {
         list.add(i);
      }
    } 
    else {
      list.add(Integer.parseInt(s));
    }
 }
System.out.println("in asc order");
Collections.sort(list);
System.out.println(list.toString());
System.out.println("in desc order");
Collections.reverse(list);
System.out.println(list.toString());
}
My output :
in asc order
[3030, 5006, 8080, 8081, 8082, 8083]
in desc order
[8083, 8082, 8081, 8080, 5006, 3030]
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With