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 a non-positive number as a limit, the method returns an array containing all elements that can be split using the passed delimiter. It’s worth noting that if we pass 0 as a limit, split() behaves as if we didn’t pass any limit. The method returns an array containing all elements that can be split using the given pattern, and trailing empty strings will be discarded.

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)

Examples

@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));
}
@Test
void whenSplitWithLimit_thenGetExpectedArray() {
    String s = "Welcome@to@Baeldung@@@";
    String[] expected1 = new String[] { "Welcome", "to", "Baeldung", "", "", "" };
    String[] expected2 = new String[] { "Welcome", "to", "Baeldung" };
    assertArrayEquals(expected1, s.split("@", -1));
    assertArrayEquals(expected2, s.split("@", 0));
}

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
announcement - icon

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

>> CHECK OUT THE COURSE

res – REST with Spring (eBook) (everywhere)