Java.lang Package Classes

Java - String split() Method



The Java string split() method returns a string array containing elements obtained by splitting the given string around matches of the given regular expression.

Syntax

public String[] split(String regex, int limit)

Parameters

regex specify the delimiting regular expression.
limit specify the result threshold, the number of elements of the array to be returned.

Return Value

Returns the array of strings computed by splitting the string around matches of the given regular expression.

Exception

Throws PatternSyntaxException, if the regular expression's syntax is invalid.

Example:

In the example below, split() method returns the string array computed after splitting the given string by specified regex expression. The limit argument is used to specify the number of elements in the array to be returned.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Hello-Cello-Hullo-Hallo-Jello";

    //split the string by "-" regex expression
    String[] Arr = MyString.split("-", 3);
    
    //print the content of the string array
    System.out.println("Arr contains: ");
    for(String str: Arr)
      System.out.println(str);
  }
}

The output of the above code will be:

Arr contains: 
Hello
Cello
Hullo-Hallo-Jello

❮ Java.lang - String