Thursday 18 September 2014

Java Programming Problem


string x = "1..5,8,11..14,18,20,26..29"

string y = "1,2,3,4,5,8,11,12,13,14,18,20,26,27,28,29"

Write a Java program to expand a given string x to y.


Solution for the above problem:


public class StringSplit {
 public static void main(String []args)
 {
 
  String source="1..5,8,11..14,18,20,26..29";
 
  String splitData[]=source.split(",");
  for(int i=0;i<splitData.length;i++)
  {
   if(splitData[i].contains(".."))
   {
    String tar[]=splitData[i].split("\\.\\.");
   
     int start=Integer.parseInt(tar[0]);
     int end=Integer.parseInt(tar[tar.length-1]);
     for(int index=start;index<=end;index++)
      System.out.print(index+" ");
   }
   else
    System.out.print(splitData[i]+" ");
  
  }
 
 
 }

}

output:
1 2 3 4 5 8 11 12 13 14 18 20 26 27 28 29

 

No comments: