Java.lang.String.split() Method

Advertisements


Description

The java.lang.String.split(String regex) method splits this string around matches of the given regular expression.

This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.

Declaration

Following is the declaration for java.lang.String.split() method

public String[] split(String regex)

Parameters

  • regex -- This is the delimiting regular expression.

Return Value

This method returns the array of strings computed by splitting this string around matches of the given regular expression.

Exception

  • PatternSyntaxException -- if the regular expression's syntax is invalid.

Example

The following example shows the usage of java.lang.String.split() method.

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {
  
    String str = "a d, m, i.n";
    String delimiters = "\\s+|,\\s*|\\.\\s*";

    // analyzing the string 
    String[] tokensVal = str.split(delimiters);

    // prints the number of tokens
    System.out.println("Count of tokens = " + tokensVal.length);
    
    for(String token : tokensVal) {
       System.out.print(token);
    } 
  }
}

Let us compile and run the above program, this will produce the following result:

Count of tokens = 5
admin



Advertisements
Advertisements