The challenge

Split a given string into different strings of equal size.

Example:

1
2
3
4
5
6
Split the below string into other strings of size #3

'supercalifragilisticexpialidocious'

Will return a new string
'sup erc ali fra gil ist ice xpi ali doc iou s'

Assumptions:

1
2
3
String length is always greater than 0
String has no spaces
Size is always positive

The solution in Java code

Option 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class InParts {
    public static String splitInParts(String s, int partLength) {
        StringBuilder sb = new StringBuilder();
        char[] c = s.toCharArray();
        int k = 0;
      
        for (int i=0; i<c.length; i++) {
          sb.append(c[i]);
          if (k==partLength-1) {
            sb.append(" ");
            k = -1;
          }
          k++;
        }
        
        return sb.toString().trim();
    }
}

Option 2:

1
2
3
4
5
6
7
8
9
public class InParts {
    public static String splitInParts(String s, int partLength) {
       StringBuilder sb = new StringBuilder(s);
       for (int i = partLength++; i < sb.length(); i += partLength){
         sb.insert(i, " ");
       }
       return sb.toString();
    }
}

Option 3:

1
2
3
4
5
public class InParts {
    public static String splitInParts(String s, int partLength) {
        return s.replaceAll("(.{"+partLength+"})(?!$)", "$1 ");
    }
}

Test cases to validate our solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import static org.junit.Assert.*;
import org.junit.Test;


public class InPartsTest {

    private static void testing(String actual, String expected) {
        assertEquals(expected, actual);
    }
   
    @Test
    public void test() {
        System.out.println("Fixed Tests splitInParts");
        String ans = InParts.splitInParts("supercalifragilisticexpialidocious", 3);
        String sol = "sup erc ali fra gil ist ice xpi ali doc iou s"; 
        testing(ans, sol);
        ans = InParts.splitInParts("HelloDude", 3);
        sol = "Hel loD ude"; 
        testing(ans, sol);
        ans = InParts.splitInParts("HelloDude", 1);
        sol = "H e l l o D u d e"; 
        testing(ans, sol);
        ans = InParts.splitInParts("HelloDude", 9);
        sol = "HelloDude"; 
        testing(ans, sol);
    }
}