The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings.

We can also pass a limit to the number of elements in the returned array. If we pass 0 as a limit, then the method will behave as if we didn’t pass any limit, returning an array containing all elements that can be split using the passed delimiter.

Further reading:

Split a String in Java

The article discusses several alternatives for splitting a String in Java.

Get Substring from String in Java

The practical ways of using the useful substring functionality in Java - from simple examples to more advanced scenarios.

A Guide To Java Regular Expressions API

A practical guide to Regular Expressions API in Java.

Available Signatures

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

Example

@Test
public void whenSplit_thenCorrect() {
    String s = "Welcome to Baeldung";
    String[] expected1 = new String[] { "Welcome", "to", "Baeldung" };
    String[] expected2 = new String[] { "Welcome", "to Baeldung" };
    
    assertArrayEquals(expected1, s.split(" "));
    assertArrayEquals(expected2, s.split(" ", 2));
}

Throws

  • PatternSyntaxException – if the pattern of the delimiter is invalid.
@Test(expected = PatternSyntaxException.class)
public void whenPassInvalidParameterToSplit_thenPatternSyntaxExceptionThrown() {
    String s = "Welcome*to Baeldung";
    
    String[] result = s.split("*");
}
Next »
Java String.startsWith()
« Previous
Java String.replaceAll()
Course – LS – All

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!