The problem
Cut up a given string into totally different strings of equal dimension.
Instance:
Cut up the under string into different strings of dimension #3
'supercalifragilisticexpialidocious'
Will return a brand new string
'sup erc ali fra gil ist ice xpi ali doc iou s'
Assumptions:
String size is at all times larger than 0
String has no areas
Dimension is at all times optimistic
The answer in Java code
Choice 1:
public class InParts {
public static String splitInParts(String s, int partLength) {
StringBuilder sb = new StringBuilder();
char[] c = s.toCharArray();
int okay = 0;
for (int i=0; i<c.size; i++) {
sb.append(c[i]);
if (okay==partLength-1) {
sb.append(" ");
okay = -1;
}
okay++;
}
return sb.toString().trim();
}
}
Choice 2:
public class InParts {
public static String splitInParts(String s, int partLength) {
StringBuilder sb = new StringBuilder(s);
for (int i = partLength++; i < sb.size(); i += partLength){
sb.insert(i, " ");
}
return sb.toString();
}
}
Choice 3:
public class InParts {
public static String splitInParts(String s, int partLength) {
return s.replaceAll("(.{"+partLength+"})(?!$)", "$1 ");
}
}
Take a look at circumstances to validate our resolution
import static org.junit.Assert.*;
import org.junit.Take a look at;
public class InPartsTest {
personal static void testing(String precise, String anticipated) {
assertEquals(anticipated, precise);
}
@Take a look at
public void check() {
System.out.println("Mounted Checks 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);
}
}