Java string split – 2 examples to learn Java split

The split method of Java

The Java split method of the String class is used to split the given string. The whole string will be broken by the given regular expression (regex).

The split method can be used to limit the split of the string by giving an int number (example shown below).

See a string split example online

Syntax of split method

The syntax of using the split Java method to split a string completely is:

public String[] split(String “regex”)

Return Value of the split method:

The split method returns an array of strings, containing the broken string.

Java string split method example

The example below uses Java split string method of the String class and breaks a string completely by a given regular expression, “and” in that case. The example uses “foreach” loop to display array items created after the split method.

Experience this online


The output will be:

name is: Mike

age is: 30

salary is: $5000

The string is broken from the “ and “ into 3 items. Then Java for each loop is used to display array items that displayed three sentences in the returned array.

Limiting split of the string

As shown in the above example, the whole string is broken by the given regex. What if you want to limit the number of breaks. For example see a string below:

“name is: Mike and age is: 30 and salary is: $5000”

If we want to split this from “ and “ for its first occurrence only? To achieve that we can limit the string split in Java by giving an int number as shown below.

Syntax of limiting the split of string

Following is the syntax of including an int number to limit the string split in Java.

public String[] split(String “regex”, int number)

The split example with limit parameter

The example below uses the split method of string with a given regular expression and the Limit number. The for loop is used to display string after the split method:

Experience this online


The output will be:

name is: Mike

age is: 30 and salary is: $5000

As you can see, the string split method only broken the given string into two “pieces” as this is specified in the split method.

Also see: Java strings

Was this article helpful?

Related Articles

Leave A Comment?