Pages

Thursday, November 7, 2013

How to Split a string at every nth position in Java

The Splitting of a String can be achieved by using the regex

Using the following code below  we can split the  string using regex
String[] thiscombo2 = st.split("(?<=\\G..)");

where
i.  The st indicates the String that needs to be split
ii.  The 3 dots after the G indicates every nth position to split. In this case, the 3 dots indicate every 3 positions.

Input : String st = "123124125134135145234235245"
Output :  123 124 125 134 135 145 234 235 245
 
But using the regex for splitting a  String will have certain delay

So to overcome this problem we provide an alternative way

The following code below will split a String at every nth position according to the user's requirements 

  private String[] splitStringEvery(String s, int interval) {
        int arrayLength = (int) Math.ceil(((s.length() / (double) interval)));
        String[] result = new String[arrayLength];
        int j = 0;
        int lastIndex = result.length - 1;
        for (int i = 0; i < lastIndex; i++) {
            result[i] = s.substring(j, j + interval);
            j += interval;
        } // Add the last bit
        result[lastIndex] = s.substring(j);
        return result;
    }


Performance Tests using the regex split and splitStringEvery()

200 characters long string - interval is 3

Using split(" (<=\\G.{"+count+"})") performance (in Milliseconds):

3,1,1,1,0,1,1,2,0,0

Using splitStringEvery() ( substring () ) performance (in Milliseconds):

1,0,0,0,0,0,0,0,0,0

No comments:

Post a Comment