Split() String Method In Java With Example

August 03, 2022
Split() String Method in Java with Example

Overview

As simple as they seem, strings have been a significant type of data in programming. It is the most commonly used data type when it comes to storing information such as names, IDs, descriptions, features, addresses etc. There are a number of methods available in Java to manipulate strings such as merging strings or searching data from a string. One such method is the splits method in Java, used to divide a string.

In this article, we will be discussing how the string split method works, how it is overloaded and various ways to effectively use the Java string split method in a Java code with the help of various examples.

new java job roles

String split() method in Java

Java string split() method allows the user to split a string into one or more substrings based on a specific Java string delimiter or a regular expression. The delimiter can be any character but the most commonly used characters are comma(,) space or a dot(.). Along with that, this method can also be used to break a string against a specified regular expression. The end result is returned in form of an array containing the separated substrings. It allows the use of a char array or a string array to store the returning substrings.

String split() method syntax

The Java split() string method has the following syntax with the string regular expression as a parameter.

Syntax:

public String split(String regex)

This method can also be overloaded by adding a limit parameter. It allows limiting the number of substrings returned by the method.

The syntax is as shown below:

public String split(String regex, int limit)

We will be discussing the working of both of these methods in detail in the coming sections,

public String[ ] split(String regex)

This version of the Java string split method has a single parameter. It just takes a regular expression as a parameter and splits the given string from the points that match the regular expression. It returns an array of substrings containing the split parts of the original string. It can throw the PatternSyntaxException if the syntax of the passed regular expression would be invalid.

See this example below demonstrating scenarios with different number of occurrences of patterns:

1. public class splitDemo01 {
2. public static void main(String args[])
3. {
4. String str = "sun and moon";
5. String[] arrOfStr = str.split(" and ");
6. 
7. for (String x : arrayOfStr)
8. System.out.println(x);
9. }
10. }
Output:

sun

moon

the pattern/regular expression “and” has just occurred once is the string hence is the only point where the string has been split.

See code below:

1. 
2. public class splitDemo02 {
3. public static void main(String args[])
4. {
5. String str = ", cat, ball, kite, bat, cap";
6. String[] arrOfStr = str.split(", ");
7. 
8. for (String x : arrOfStr)
9. System.out.println(x);
10. }
11. }
Output

cat

Ball

Kite

Bat

It can be seen that 4 substrings are returned because “, “is present that many times in the string.

Splitting a string using a regex

The use of a regex offers a lot more options to split a string in Java. The occurrence of either of the characters present in the set of regexes passed as a parameter would split the input string.

See the code example below:

1. public class splitDemo03 {
2. 
3. public static void main(String args[])
4. {
5. String str = "apples_oranges kiwis#lemons?pears.grapes ";
6. String[] arrayOfStr = str.split("s[_ ?.#]");
7. 
8. for (String x : arrOfStr)
9. System.out.println(x);
10.  }
11. }

In the above example, there is an “s” character as well along with the set thus occurrence of either of the character with the “s” will split the string. As a result, see the output below where a string is separated whenever either of the characters specified in the set is encountered along with “s”.

Output

apple

orange

kiwi

lemon

pear

grape

Splitting a string using a delimiter

A delimiter would be used just like a regular expression in this method. The original string will be divided every time the delimiter will occur. A common practice of using a delimiter is when we have to extract specific data from a string that contains several data values separated by a delimiter.

See this example below:

1. public class splittingwithDelimiter {
2. public static void main(String args[])
3. {
4. String str = " The quick brown fox jumps over the lazy dog";
5. String[] arrOfStr = str.split(" ");
6. 
7. for (String x : arrOfStr)
8. System.out.println(x);
9. }
Output:

the

quick

brown

fox

jumps

over

the

lazy

dog

public String split(String regex, int limit)

This overloaded version of the Java string split method consists of two parameters, a regular expression same as the earlier version and a limit value in Integer.  The limit value plays an important role here as it acts as a resulting threshold. It is an integer value representing the maximum number of values in the array.  It means that you can now control the number of substrings created regardless of the occurrence of matching delimiter or regular expression.

Limit Values

As limit is an integer value, it can be any whole number but we can categorize the limit values into the following three types based on different types of functionalities offered,

  1. Greater than 0
  2. Less than 0
  3. Equals to 0

1. Limit is greater than 0

In this case, the regular expression will be applied at most “limit – 1” times. The length of the returned array will not be more than the size of the string and the last element of the returned array will be the remaining input string beyond the last matched pattern.

See this code demonstration below:

1. // Java program to demonstrate the working of split() method with a limit greater than 0.
2. public class limit>0 {
3. public static void main(String args[])
4. {
5. String str = "apples, grapes, peaches, lemons, oranges, kiwis";
6. String[] arrayOfStr = str.split(", ", 4);
7.
8. for (String x : arrayOfStr)
9. System.out.println(x);
10. }
11. }
Output:

apples

grapes

peaches

lemons, oranges, kiwis

The output represents where the number of delimiters in the string is less than the limit thus the last element of the array contains the remaining string.

2. Limit is less than 0

If the limit value is set as a negative value, the input string will be separated as many times as the delimiter will be found and the returning string array can be of any required size.

See code below:

1.	// Java program to demonstrate working of split() method with a negative limit value.
2.	public class limit<0 {
3.	public static void main(String args[])
4.	{
5.	String str = "apples, grapes, peaches, lemons, oranges, kiwis, ";
6.	String[] arrayOfStr = str.split(", ", -3);
for (String x : arrayOfStr)
7.	System.out.println(x);
8.	}
9.	}
Output:

apples

grapes

peaches

lemons

oranges

kiwis

3. limit is equal to 0

The result of the limit value set as 0 would be the same as using the split method without a limit parameter. Similar to a negative limit value, the string will be divided as many times as the delimiter occurs and the returned array can also be of any size but the only difference from using a negative value is that the trailing empty strings are always discarded.

It would be more suitable to use the method version without the limit parameter if you are aiming to only use the 0 as the limit value in your code.

See code below:

1. // Java program to demonstrate the working of the split() method with 0 limit value.
2. 
3. public class limit=0 {
4. public static void main(String args[])
5. {
6. String str = "apples, grapes, peaches, lemons, oranges, kiwis, , , , ";
7. String[] arrayOfStr = str.split(", ", 0);
8. 
9. for (String x : arrayOfStr)
10. System.out.println(x);
11. }
12. }
Output:

apples

grapes

peaches

lemons

oranges

kiwis

Wrapping it up

In this article, we have covered the Java string split() method. As discussed, it covers a wide range of features when it comes to working with strings and splitting them to extract a specific substring from a string. The Java string split method offers a variety of ways to split a string. We have covered the functionality, syntax and usage of both types of string split() methods along with the ways of using the limit parameter to restrict the size of the returning array.

Also Read: Generate Random String in Java

Despite this extensive walkthrough, this was just an introduction to the string split method in Java. You can explore it further to understand how you can use it in your code as per your requirements when dealing with the string data type.

new Java jobs

author

shaharyar-lalani

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.


Candidate signup

Create a free profile to start finding your next opportunity.

Sign up to get hired.

Employer signup

Sign up and find your next team member.

Sign up to hire.

How it works

Learn more about Xperti's unique talent matching process.

See how it works.

Join our community

Connect and Engage with Technology Enthusiasts.

Join the community.