StringTokenizer Splits Delimiters
Split text with StringTokenizer, including the returnDelims mode that keeps separators as tokens, and contrast it with String.split.
Code
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String line = "GET /api/users?page=2 HTTP/1.1";
// consecutive delimiters are skipped, so no empty tokens appear
StringTokenizer tokens = new StringTokenizer(line, " ");
System.out.println("count: " + tokens.countTokens());
while (tokens.hasMoreTokens()) {
System.out.println("token: " + tokens.nextToken());
}
// returnDelims keeps each separator as its own token
StringTokenizer withDelims = new StringTokenizer("a,b;c", ",;", true);
while (withDelims.hasMoreTokens()) {
System.out.print("[" + withDelims.nextToken() + "]");
}
System.out.println();
// an explicit -1 limit keeps the trailing empty field
System.out.println("split(-1) length: " + "a,b,".split(",", -1).length);
System.out.println("tokenizer count: " + new StringTokenizer("a,b,", ",").countTokens());
}
}How the snippet works
The snippet is organized around the class Main and the function main.
Iteration happens inside while (tokens.hasMoreTokens()) — everything outside it runs once.
Watch out for
- Zero third-party dependencies — the runtime provides every API used here.
Putting it to use
The primary signature is public static void main(String[] args)
Expect labeled output — count:, token:, split(-1) length: — when the file runs.
Core lines
StringTokenizer withDelims = new StringTokenizer("a,b;c", ",;", true);
StringTokenizer tokens = new StringTokenizer(line, " ");
String line = "GET /api/users?page=2 HTTP/1.1";
Interactive Tools for This Topic
FAQ
- What does StringTokenizer Splits Delimiters print when run?
- Execute the whole file; each printed line is prefixed with a label like `count:`, `token:`, `split(-1) length:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.