Split String into Parts in Java

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'
Code language: PHP (php)

Assumptions:

String length is always greater than 0 String has no spaces Size is always positive
Code language: JavaScript (javascript)

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(); } }
Code language: Java (java)

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(); } }
Code language: Java (java)

Option 3:

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

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); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments