Java String split(String regex,int limit) method example

HQ » Java Tutorial » java.lang » String » split(String regex,int limit) method example
Java String split(String regex,int limit) method example 2018-02-19T13:02:51+00:00

java.lang.String split(String regex, int limit)

Description :

This java tutorial shows how to use the split() method of String class of java.lang package. This method returns a character array which corresponds to the result of splitting the String object given a java regular expression as a method parameter and the tokens are limited using the method parameter limit.

Method Syntax :

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

Parameter Input :

DataType Parameter Description
String regex The java regular expression to be used in evaluating how to split the string
int limit the maximum number of tokens the string will be splitted

Method Returns :

This String split() method with argument regex returns an array of String. The regex parameter will be used in evaluating how we can split the String object and the number of tokens will be limited with the parameter limit.

Compatibility Version :

Requires Java 1.4 and up

Exception :

PatternSyntaxException

This exception will be thrown if and only if the regex pattern specified on the method parameter is invalid.

Discussion :

The string split method is helpful only on circumstances that we would want only a specific part of a string to be tokenize. The split string is helpful in converting a string object delimited with regex pattern into tokens. These tokens are stored in an array object, thus we will have now individual access for each string elements.

Java Code Example :

This example source code demonstrates the use of split(regex,limit) method of String class. Basically it just converts a String object in the format Name:AGE:Country into a String array. On the example we have provided there are 3 possible tokens that we could get, however we put only a limit of 2 thus our array will be 2 elements only. The first element would contain “Name” token and the second token would be “AGE:Country”.

Sample Output :

Running the split(String regex,int limit) method example source code of String class will give you the following output

string split method example

string split method example

Exception Scenario :

Similar Method :

  • java.lang.String split(String regex)

Suggested Reading List :

 

Contact Info

Singapore

Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close