Split() String Method in Java with Examples
The string split() method splits the given string around matches of the given regular expression.
1. public String [ ] split ( String regex, int limit )
Example 1:
// Java program to demonstrate working of split(regex,
// limit) with small limit.
public class GFG {
public static void main(String args[])
{
String str = "geekss@for@geekss";
String[] arrOfStr = str.split("@", 2);
for (String a : arrOfStr)
System.out.println(a);
}
}
output:
geekss
for@geekss
Example 2:
// Java program to demonstrate working of split(regex,
// limit) with high limit.
public class GFG {
public static void main(String args[])
{
String str = "geekss@for@geekss";
String[] arrOfStr = str.split("@", 5);
for (String a : arrOfStr)
System.out.println(a);
}
}
output:
geekss
for
geekss
Example 3:
// Java program to demonstrate working of split(regex,
// limit) with negative limit.
public class GFG {
public static void main(String args[])
{
String str = "geekss@for@geekss";
String[] arrOfStr = str.split("@", -2);
for (String a : arrOfStr)
System.out.println(a);
}
}
output:
geekss
for
geekss
Example 4:
// Java program to demonstrate working of split(regex,
// limit) with high limit.
public class GFG {
public static void main(String args[])
{
String str = "geekss@for@geekss";
String[] arrOfStr = str.split("s", 5);
for (String a : arrOfStr)
System.out.println(a);
}
}
output:
geek
@for@geek
Example 5:
// Java program to demonstrate working of split(regex,
// limit) with negative limit.
public class GFG {
public static void main(String args[])
{
String str = "geekss@for@geekss";
String[] arrOfStr = str.split("s", -2);
for (String a : arrOfStr)
System.out.println(a);
}
}
output:
geek
@for@geek
Example 6:
// Java program to demonstrate working of split(regex,
// limit) with 0 limit.
public class GFG {
public static void main(String args[])
{
String str = "geekss@for@geekss";
String[] arrOfStr = str.split("s", 0);
for (String a : arrOfStr)
System.out.println(a);
}
}
output:
Geek
@for@geek