Split String into Parts in Java

1 min read 264 words

The challenge

Split a given string into different strings of equal size.

Example:

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:

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

The solution in Java code

Option 1:

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:

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:

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

Test cases to validate our solution

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);
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts