How to Split a String in Java?

In Java, you can split a string into multiple substrings based on a specified delimiter. The resulting substrings are stored in an array. This can be a useful feature when you need to manipulate text data.

The String class provides the split() method to split a string. The method takes a regular expression as an argument and returns an array of substrings.

Here’s the syntax of the split() method in Java:

String[] parts = inputString.split(delimiter);

Java String.split() Signature

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

Here, inputString is the string that you want to split, and delimiter is the regular expression that you want to use as a separator.

Let’s take an example to see how the split() method works:

String sentence = "The quick brown fox jumps over the lazy dog";
String[] words = sentence.split(" ");

In this example, we have a string sentence that contains a sentence. We want to split this sentence into words, so we use the space character as the delimiter. The resulting array words will contain each word as an element.

Here is the output doing a foreach loop for the variable words

for (String word : words) {


How to Split a String in Java using a Regular Expression

You can also split a string using a regular expression that matches a pattern. For example, let’s say you have a string that contains multiple lines of text separated by a new line character \n. You can split this string into an array of lines using the following code:

String text = "Line 1\nLine 2\nLine 3\n";
String[] lines = text.split("\\r?\\n");

In this example, we use the regular expression \\r?\\n as the delimiter to split the string into lines. The \\r character matches a carriage return, and the \\n character matches a line feed. The ? character makes the preceding expression optional, so the regular expression matches both \r\n and \n line endings.

You can also limit the number of substrings in the resulting array by specifying a limit parameter. For example:

String text = "apple,banana,orange,grape";
String[] fruits = text.split(",", 2);

In this example, we use the comma character as the delimiter to split the string into substrings. The 2 parameter limits the resulting array to contain at most two substrings. The resulting array will contain “apple” as the first element and “banana,orange,grape” as the second element.

In conclusion, splitting a string in Java is easy using the split() method of the String class. You can use a simple delimiter or a regular expression to split the string into multiple substrings, and limit the number of substrings in the resulting array if necessary.

Share your love

Leave a Reply

Your email address will not be published. Required fields are marked *