Split Limit Keeps Trailing Fields
Split structured strings with the two-arg split limit: -1 preserves trailing empty fields that the default split silently drops.
Code
public class FieldParser {
public static void main(String[] args) {
// CSV 风格记录:末列允许为空
String row = "id=42,name=ada,note=";
// 无 limit:尾部空串被静默丢弃,note 列消失
String[] defaultSplit = row.split(",");
System.out.println("default fields = " + defaultSplit.length);
// 第二个参数是 limit 上限:-1 保留全部字段(含尾部空串),列位对齐
String[] all = row.split(",", -1);
System.out.println("kept fields = " + all.length);
for (int i = 0; i < all.length; i++) {
String field = all[i];
int eq = field.indexOf('=');
String key = field.substring(0, eq);
String value = field.substring(eq + 1);
System.out.println(i + ": " + key + " = [" + value + "]");
}
}
}How it works
Split Limit Keeps Trailing Fields is built around the class FieldParser and the function main.
Repetition is confined to for (int i = 0; i < all.length; i++) — the rest of the file is straight-line.
Using it
The demo output is labeled (default fields =, kept fields =), so every printed line maps back to its originating operation.
Key statements
String[] defaultSplit = row.split(",");
String value = field.substring(eq + 1);
String row = "id=42,name=ada,note=";
Interactive Tools for This Topic
FAQ
- What does Split Limit Keeps Trailing Fields print when run?
- No setup needed: run the file and look for labeled lines like `default fields =`, `kept fields =` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.