I tried to search online to solve this question but I didn\'t found anything.
I wrote the following abstract code to explain what I\'m asking:
String
Quick Hack
private String[] splitByNumber(String s, int size) {
if(s == null || size <= 0)
return null;
int chunks = s.length() / size + ((s.length() % size > 0) ? 1 : 0);
String[] arr = new String[chunks];
for(int i = 0, j = 0, l = s.length(); i < l; i += size, j++)
arr[j] = s.substring(i, Math.min(l, i + size));
return arr;
}
Using simple java primitives and loops.
private static String[] splitByNumber(String text, int number) {
int inLength = text.length();
int arLength = inLength / number;
int left=inLength%number;
if(left>0){++arLength;}
String ar[] = new String[arLength];
String tempText=text;
for (int x = 0; x < arLength; ++x) {
if(tempText.length()>number){
ar[x]=tempText.substring(0, number);
tempText=tempText.substring(number);
}else{
ar[x]=tempText;
}
}
return ar;
}
Usage : String ar[]=splitByNumber("nalaka", 2);
I think that what he wants is to have a string split into substrings of size 4. Then I would do this in a loop:
List<String> strings = new ArrayList<String>();
int index = 0;
while (index < text.length()) {
strings.add(text.substring(index, Math.min(index + 4,text.length())));
index += 4;
}
Try this solution,
public static String[]chunkStringByLength(String inputString, int numOfChar) {
if (inputString == null || numOfChar <= 0)
return null;
else if (inputString.length() == numOfChar)
return new String[]{
inputString
};
int chunkLen = (int)Math.ceil(inputString.length() / numOfChar);
String[]chunks = new String[chunkLen + 1];
for (int i = 0; i <= chunkLen; i++) {
int endLen = numOfChar;
if (i == chunkLen) {
endLen = inputString.length() % numOfChar;
}
chunks[i] = new String(inputString.getBytes(), i * numOfChar, endLen);
}
return chunks;
}
Here's a succinct implementation using Java8 streams:
String text = "how are you?";
final AtomicInteger counter = new AtomicInteger(0);
Collection<String> strings = text.chars()
.mapToObj(i -> String.valueOf((char)i) )
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 4
,Collectors.joining()))
.values();
Output:
[how , are , you?]