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"]
More Java Articles
- How to Remove the Last Character in a String in Java
- How to Remove the First Character in a String in Java
- How to Get the Substring Before a Character in Java
- How to Pass Dynamic Number of Parameters in Java
- How to Use Generics with Abstract Classes in Java For Different Parameter Types
- How to Replace the String Between Two Characters in Java
- How to Print Elements of a List in Java Without Loops
- How to Ignore Test Cases in JUnit
- How to Add Multiple Elements to List At Once in Java