How to Split a String Only on the First Occurrence of Delimiter ?

Gain Java Knowledge
1 min readMay 10, 2022

In this tutorial we learn how to split based on delimiter within limit.

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

Suppose we run split() on a string.

String str = “This is a java program”;
str.split(“ “);
This will yield a string array that looks something like this:

[“This”, “is”, “a”, “java” “program”]

But now our requirement is that , we want output in this format :

[“This”, “is a java program”]

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 java program”;
str.split(“ “, 2); // [“This”, “is a java program”]

System.out.println(“1st : “+array[0]); // 1st : This
System.out.println(“2nd : “+array[1]); // 2nd : is a java program

Sample Program

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

No responses yet