Here we use a method that breaks a string into n elements in length. (If the string length cannot be exactly divided by n, the last element will be shorter.)
public static String[] splitInEqualParts(final String s, final int n){ if(s == null){ return null; } final int strlen = s.length(); if(strlen < n){
Test code:
private static void printArray(final String[] arr){ System.out.print("["); boolean first = true; for(final String item : arr){ if(first) first = false; else System.out.print(", "); System.out.print("'" + item + "'"); } System.out.println("]"); } public static void main(final String[] args){ printArray(splitInEqualParts("Hound dog", 2)); printArray(splitInEqualParts("Love me tender", 3)); printArray(splitInEqualParts("Jailhouse Rock", 4)); }
Output:
['Dog', 'dog']
['Love', 'me te', 'nder']
['Jail', 'hous', 'e Ro', 'ck']
Sean Patrick Floyd
source share