Java String split()

The split() method divides the string at the specified regex and returns an array of substrings.

Example


Syntax of String split()

The syntax of the string split() method is:

string.split(String regex, int limit)

Here, string is an object of the String class.


split() Parameters

The string split() method can take two parameters:

  • regex - the string is divided at this regex (can be strings)
  • limit (optional) - controls the number of resulting substrings

If the limit parameter is not passed, split() returns all possible substrings.


split() Return Value

  • returns an array of substrings

Note: If the regular expression passed to split() is invalid, the split() method raises PatternSyntaxExpression exception.


Example 1: split() Without limit Parameter

Output

result = [a, b, c, d:e]

Here, we split the string at ::. Since the limit parameter is not passed, the returned array contains all the substrings.


split() With limit Parameter

  • If the limit parameter is 0 or negative, split() returns an array containing all substrings.
  • If the limit parameter is positive (let's say n), split() returns the maximum of n substrings.

Example 2: split() With limit Parameter

Output

result when limit is -2 = [a, bc, de, fg, h]
result when limit is 0 = [a, bc, de, fg, h]
result when limit is 2 = [a, bc:de:fg:h]
result when limit is 4 = [a, bc, de, fg:h]
result when limit is 10 = [a, bc, de, fg, h]

Note: The split() method takes regex as the first argument. If you need to use special characters such as: \, |, ^, *, + etc, you need to escape these characters. For example, we need to use \\+ to split at +.


Example 3: split() at the + character

Output

result = [a, e, f]

Here, to split a string at +, we have used \\+. It's because + is a special character (has a special meaning in regular expressions).