Java Notes
Java Notes
limit > 0 – If this is the case, then the pattern will be applied at most limit-1 times,
the resulting array’s length will not be more than n, and the resulting array’s last
entry will contain all input beyond the last matched pattern.
limit < 0 – In this case, the pattern will be applied as many times as possible, and
the resulting array can be of any size.
limit = 0 – In this case, the pattern will be applied as many times as possible, the
resulting array can be of any size, and trailing empty strings will be discarded.
Here’s how it works:
Let the string that is to be split is – geekss@for@geekss
Regex Limit Result
@ 2 {“geekss”, ”for@geekss”}
Following are the Java example codes to demonstrate the working of split()
Example 1:
Java
{
System.out.println(a);
}
Output
geekss
for@geekss
Example 2:
Java
{
System.out.println(a);
}
Output
geekss
for
geekss
Example 3:
Java
{
String str = "geekss@for@geekss";
System.out.println(a);
}
Output
geekss
for
geekss
Example 4:
Java
{
System.out.println(a);
}
Output
geek
@for@geek
Example 5:
Java
{
System.out.println(a);
}
Output
geek
@for@geek
Example 6:
Java
{
System.out.println(a);
}
Output
geek
@for@geek
{
String str
System.out.println(a);
}
Output
GeeksforGeeks
A Computer Science Portal
Example 2:
Java
{
System.out.println(a);
}
Output
Geeks
Geeks
Students
It can be seen in the above example that the pattern/regular expression “for” is applied
twice (because “for” is present two times in the string to be split)
Example 3:
Java
{
for (String a : arrOfStr)
System.out.println(a);
}
Output
Geeks
for
Geeks
Example 4:
Java
{
String[] arrOfStr
// no output...
}
Output
Geeks
for
Geeks
Example 5:
Java
{
System.out.println(a);
}
}
Output
Geek
In the above example, trailing empty strings are not included in the resulting array
arrOfStr.
Example 6:
Java
{
System.out.println(a);
}
Output
Geeks
Geeks
In the above example, the trailing spaces (hence not empty string) become a string in
the resulting array arrOfStr.
Example 7:
Java
{
System.out.println(a);
}
Output
word1
word2
word3
word4
word5
word6
In the above example, words are separated whenever either of the characters specified
in the set is encountered.
This article is contributed by Vaibhav Bajpai. If you like GeeksforGeeks and would
like to contribute, you can also write an article using write.geeksforgeeks.org. See your
article appearing on the GeeksforGeeks main page and help other Geeks. Please write
comments if you find anything incorrect or if you want to share more information about
the topic discussed above