How to split the string based on delimiter in Java?

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.

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

RegexLimitResult
&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

Output

The Avengers
Marvel Studios
USA

Example : Split method with limit in Java

Output

The Avengers
Marvel Studios,USA

Recommended Articles