From your question:
There is string with fixed length and it has to be spitted by 15 characters each record. The results should be placed in List
.
String.split()
isn't really suitable for something like this. It's designed to split on a delimiter, which "every 15 characters" is not.
You're looking for the functionality in String.substring()
, which returns a String
that is the sequence between [beginIndex, endIndex)
.
With this method:
public static List<String> splitByIndex(String toSplit, int index) {
List<String> result = new ArrayList<String>();
for (int i = 0; i < toSplit.length(); i += index) {
if (i + index < toSplit.length()) {
result.add(toSplit.substring(i, i + index));
} else {
result.add(toSplit.substring(i, toSplit.length() - 1));
}
}
return result;
}
You can split a String
into a List<String>
by a given number of characters. This example code:
String a1 = "I'm the fixed length string that needs to be split by 15 characters.";
List<String> list = splitByIndex(a1, 15);
System.out.println(list);
will output:
[I'm the fixed l, ength string th, at needs to be , split by 15 cha, racters]