Reputation: 5317
I want to split strings into fixed-length, for example, split by 20 characters and if after splitting length is less than 20 characters, then fill the string with whitespace up to 20 characters.
public static List<String> splitEqually(String text, int size) {
List<String> ret = new ArrayList<String>((text.length() + size - 1) / size);
for (int start = 0; start < text.length(); start += size) {
ret.add(text.substring(start, Math.min(text.length(), start + size)));
}
return ret;
}
I used the above code to split by equal size.
Upvotes: 0
Views: 844
Reputation: 3728
with lambda
String blanks20 = " ";
ArrayList<String> fixed20 = list.stream().collect( Collector.of( ArrayList::new,
(l, s) -> {
for(int i = 0; ; s = s.substring( 20 )) {
l.add( (s + blanks20).substring( i, i + 20 ) );
if( s.length() < 20 )
break;
} },
(l, r) -> { l.addAll( r ); return( l ); } ) );
Upvotes: 0
Reputation: 159106
Only the last value might not be of the given size, so pad it with spaces if needed, after the loop.
public static List<String> splitFixedWidth(String text, int width) {
List<String> ret = new ArrayList<>((text.length() + width - 1) / width);
for (int start = 0; start < text.length(); start += width) {
ret.add(text.substring(start, Math.min(text.length(), start + width)));
}
if (! ret.isEmpty()) {
String lastValue = ret.get(ret.size() - 1);
if (lastValue.length() < width) {
lastValue += " ".repeat(width - lastValue.length());
ret.set(ret.size() - 1, lastValue);
}
}
return ret;
}
In Java versions below 11, use:
if (lastValue.length() < width) {
char[] buf = new char[width];
lastValue.getChars(0, lastValue.length(), buf, 0);
Arrays.fill(buf, lastValue.length(), width, ' ');
ret.set(ret.size() - 1, new String(buf));
}
Or shorter but less efficient:
if (lastValue.length() < width) {
ret.set(ret.size() - 1, String.format("%-" + width + "s", lastValue));
}
Upvotes: 2
Reputation: 967
This code will resolve your problem.
public static List<String> splitEqually(String text, int size) {
List<String> ret = new ArrayList<String>((text.length() + size - 1) / size);
StringBuilder str1 = new StringBuilder();
for (int start = 0; start < text.length(); start += size) {
String temp = text.substring(start, Math.min(text.length(), start + size));
if (temp.length() == size) {
ret.add(temp);
System.out.println(temp.length());
} else {
int n = size - temp.length();
str1.append(temp);
for (int j =0 ; j< n ; j++){
str1.append(" ");
}
System.out.println(str1.length());
ret.add(str1.toString());
}
}
return ret;
}
Upvotes: 3