Java

Java String split() Method

Sometimes the array contains a huge amount of data which is hard to handle. To do this, an extensive amount of data needs to be divided into different segments or chunks for easy understanding and handling. For this purpose, thanks to Java provides a “split()” method that is used to divide the data into subsections.

This post will explain the string split() method in Java.

What is the Java String split() Method?

The string split() method is used to divide a given text into segments or different parts that match the specified regular expression. Also, it produces a string array after separating against the passed regular expression.

How to Utilize the Java String split() Method?

To utilize the Java string split() method, follow the below-stated syntax:

string.split(regex, limit)

 

In the above syntax:

  • string” is an object of the String class.
  • regex” denotes the regular expression on which bases the string can be split.
  • limit” determines the total number of substrings that split.

Example 1: Using split() by Defining Limit

In this example, we will use the “split()” method by defining the limit and the part of the string from where we want to split. To do so, create a string by specifying a name and set the string as the value:

String = "welcome to linuxhint tutorial website";

 

Then, define an array named “arrOfStr” and invoke the “split()” method. Pass the part of the string “linuxhint” and the limit for split “2” as the argument:

String[] arrOfStr = string.split("linuxhint", 2);

 

Utilize the “for” loop and set the condition:

for (String b : arrOfStr)

 

Invoke the “println()” method and pass the “b” as an argument to display the output on the console:

System.out.println(b);

 

It can be observed that the string is divided into two parts:

Example 2: Using split() by Specifying String regex

You can also use the split() method by specifying the string regex. To do so, make a string with a name and set the value according to your preference:

String string = "Welcome: This is Linuxhint tutorial website";

 

Create an array and utilize the split() method. Then, pass “:” as the regex parameter from where it is required to split the string:

String[] arrayOfStr = string.split(":");

 

Specify the condition with the help of the “for” iterator:

for (String ar : arrayOfStr)

 

Print the output on the console by invoking the println() method:

System.out.println(ar);

 

As a result, the string is split into two parts:

You have learned about the Java string split() method.

Conclusion

The “split()” is the built-in method of Java that is used to split the string. To do so, you can split the string by specifying the regex and setting the limit in an integer data type. It produces a string array after separating against the specified regular expression. This tutorial has stated the string split() method in Java.

About the author

Hafsa Javed