How to Split a String Only on the First Occurrence of Delimiter ?
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