How to split the string based on delimiter in Java?
Contents
Split method in Java
The String split method in Java is used to divide the string around matches of the given regular expression. It will returns the array of strings after splitting an input string based on the delimiter or regular expression.
1 |
public String[] split(String regex,int limit) |
Parameters:
- regex – the delimiting character or regular expression
- limit – Limit the number of string to be splitted. It is an optional argument.
The limit is controls the number of times the pattern needs to be applied .
- limit > 0 : The pattern will be applied for n-1 times . The returned array’s length will be no greater than n, and the array’s last entry will contain all input beyond the last matched delimiter
- limit < 0 : The pattern will be applied as many times as possible and the array can have any length.
- limit = 0 : The pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Explanation for the limit values with examples
The input string is : revisit&class&program&examples
Regex | Limit | Result |
& | 2 | {“revisit”,”class&program&examples”} |
& | 5 | {“revisit”,”class”,”program”,”examples”} |
& | -2 | {“revisit”,”class”,”program”,”examples”} |
Returns
The array of strings computed by splitting the input string around matches of the given regular expression
Example 1 : Split the string based on delimiter in Java
1 2 3 4 5 6 7 8 9 10 11 12 |
// Java program to split the string based on delimiter comma(,) public class SplitStr { public static void main(String[] args) { String source = "The Avengers,Marvel Studios,USA"; // Split method matches the given delimiter and split the string based on it. String[] output = source.split(","); for(String splitString : output){ System.out.println(splitString); } } |
Output
The Avengers
Marvel Studios
USA
Example : Split method with limit in Java
1 2 3 4 5 6 7 8 9 10 |
public class SplitStr { public static void main(String[] args) { String source = "The Avengers,Marvel Studios,USA"; // Split method with limit as 2 String[] output = source.split(",",2); for(String splitString : output){ System.out.println(splitString); } } |
Output
The Avengers
Marvel Studios,USA
Recommended Articles