How to Split a String Over Only the First Occurrence in Java


We know we can split a string over some delimiter in Java.

Suppose we run split() on a string.

String str = "This is a string";
str.split(" ");

This will yield a string array that looks something like this:

["This", "is", "a", "string"]

What if we want an array that looks like this?

["This", "is a string"]

We are splitting over only the first occurrence of the delimiter. We can do this using the second parameter of the split() function, which is the limit.

String str = "This is a string";
str.split(" ", 2); // ["This", "is a string"]
str.split(" ", 3); // ["This", "is", "a string"]