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
Get Substring from String in Java
A Guide To Java Regular Expressions API
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("*");
}