String.splitWithDelimiters Keeps Separators

Split text with JDK 21 String.splitWithDelimiters so matched separators stay in odd array slots, comparing positive, zero, and negative limit rules.

JavaData Integrity

Code

snippet
import java.util.Arrays;

public class DelimiterTokenSplit {

    public static void main(String[] args) {
        String expr = "10+20-30*40";

        // Even slots hold tokens; odd slots preserve each matched operator separator
        String[] all = expr.splitWithDelimiters("[+*/-]", 0);
        System.out.println("tokens+delims:  " + Arrays.toString(all));

        // limit=3 stops after 2 delimiters (3 token slots), keeping the remaining suffix
        String[] capped = expr.splitWithDelimiters("[+*/-]", 3);
        System.out.println("limit=3 capped: " + Arrays.toString(capped));

        // Trailing separator: limit=0 drops the final empty token but retains the delimiter
        String trailing = "a+b+";
        System.out.println("limit=0 tail:   " + Arrays.toString(trailing.splitWithDelimiters("\\+", 0)));
        System.out.println("limit=-1 tail:  " + Arrays.toString(trailing.splitWithDelimiters("\\+", -1)));

        // Contrast with String.split, which discards every matched separator
        System.out.println("plain split:    " + Arrays.toString(expr.split("[+*/-]")));
    }
}

Inside the routine — String.splitWithDelimiters Keeps Separators

Under the hood: the class DelimiterTokenSplit and the function main.

Points of care

  • Uses solely built-in runtime APIs, removing external package supply-chain review overhead.

Using it

Primary invocation prototype opens as public static void main(String[] args)

The file’s steps show up in the output as tokens+delims:, limit=3 capped:, limit=0 tail:.

Key statements

String[] capped = expr.splitWithDelimiters("[+*/-]", 3);
String[] all = expr.splitWithDelimiters("[+*/-]", 0);
String expr = "10+20-30*40";

Interactive Tools for This Topic

FAQ

What does String.splitWithDelimiters Keeps Separators print when run?
Running the file directly is enough — expect labeled output lines such as `tokens+delims:`, `limit=3 capped:`, `limit=0 tail:`.