Java String split()

Java, the split() method of the String class is used to split a string into multiple substrings based on a specified delimiter. The split() method takes the delimiter as an argument and returns an array of strings that are separated by that delimiter.

Syantax
public String[] split(String regex)

regex : regular expression to be applied on string.

Returns: array of strings

Example
class TestClass{ public static void main (String[] args){ String str = "007-034456-0076"; String[] parts = str.split("-"); for (String x : parts) System.out.println(x); } }
Output
007 034456 0076

Java String split() is based on regex expression, a special attention is needed with some characters which have a special meaning in a regex expression.

The split() method provides a convenient way to extract individual pieces of information from a string based on a specific pattern or delimiter. It is commonly used in various string manipulation and parsing tasks in Java programming.

Spliting string with limit

Syntax
public String split(String regex, int limit)

You can set a limit the output strings.

Example
class TestClass{ public static void main (String[] args){ String str = "1111-2222-3333-4444-5555"; String[] parts = str.split("-",2); for (String x : parts) System.out.println(x); } }
Output
1111 2222-3333-4444-5555

There are situation that several characters being used as delimiters.

Example
class TestClass{ public static void main (String[] args){ String str = "(a+b)-c/d"; String[] parts = str.split("[()+-/]+"); for (String x : parts) System.out.println(x); } }
Output
a b c d

How to split a String by space

Java String.split() method is based upon regular expressions. So provide "\\s+" as split parameter.

Example
class TestClass{ public static void main (String[] args){ String str = "Java String Tutorial"; String[] parts = str.split("\\s+"); for (String x : parts) System.out.println(x); } }
Output
Java String Tutorial

Conclusion

The split() method in Java String is used to divide a string into an array of substrings based on a specified delimiter. It returns the substrings as elements of the resulting array, allowing easy separation and manipulation of components within the original string.