In this Java tutorial, you will learn how to split a string using the String.split() method. The examples cover delimiters, regular expressions, spaces, dots, limits, trailing empty values, conversion to a list, and splitting at a specific index.
Java – Split String
To split a string in Java, use the split() method of the String class. The method separates the string wherever its regular-expression delimiter matches and returns the parts in a String[] array.
For example, if a string contains values separated by hyphens, commas, spaces, or another known delimiter, split() can separate those values. Because the delimiter argument is interpreted as a regular expression, characters such as a dot or pipe need special handling when you want to match them literally.
The original string is not modified. split() returns a new array containing the resulting substrings.
Java String split() method syntax
The syntax of String split() method is given below.
String.split(String regex, int limit)
The split() method is available in two commonly used forms: split(String regex) and split(String regex, int limit). The one-argument form behaves like calling the two-argument form with a limit of 0.
| Parameter | Description |
|---|---|
regex | [Mandatory] A String containing the regular expression used to find separators. A literal delimiter such as - or , can be used directly when it has no special regular-expression meaning. |
limit | [Optional] An int that controls how many elements may be returned and how trailing empty strings are handled. When limit > 0, the pattern is applied at most limit - 1 times, so the returned array contains at most limit elements. |
The regex argument is not simply a delimiter string; Java treats it as a regular expression. A plain character such as a hyphen in the examples below works directly, while a regular-expression metacharacter such as . must be escaped or quoted if you want to split on the literal character.
Java String split() examples
1. Split a Java string by a character delimiter
This example uses a hyphen as a single-character delimiter. Each hyphen separates one part of the string from the next.
Example.java
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
//two strings
String str = "aba-cdc-abc";
String separator = "-";
//split string
String[] splits = str.split(separator);
System.out.print(Arrays.toString(splits));
}
}
The output is:
[aba, cdc, abc]
The delimiter positions and resulting parts can be visualized as follows.
aba-cdc-abc //string
- - //separators
______________
aba cdc abc //splits
______________
Result = [aba, cdc, abc]
Here, every hyphen is treated as a separator. The separator itself is not included in the returned strings.
2. Split a Java string with a regular expression
The delimiter passed to split() can be a regular expression. This makes it possible to split on more than one separator pattern.
Here, the regular expression is "[abc]-". It matches "a-", "b-", or "c-".
Example.java
import java.util.Arrays;
/**
* Java Example Program to Split a String
*/
public class Example {
public static void main(String[] args) {
//two strings
String str = "aba-cdc-abc";
//regular expression for separator
String separator = "[abc]-";
//split string
String[] splits = str.split(separator);
System.out.print(Arrays.toString(splits));
}
}
The output is:
[ab, cd, abc]
The regular-expression matches and resulting parts are shown below.
aba-cdc-abc //string
a- c- //separators
______________
ab cd abc //splits
______________
Result = [ab, cd, abc]
The character class [abc] matches one character: a, b, or c. The following hyphen is part of the same separator pattern.
3. Limit Java String split() to a maximum number of elements
Use the two-argument form of split() when the returned array should contain no more than a specific number of elements.
In this example, the limit is 4. The delimiter can therefore be applied at most three times, and the remaining text becomes the fourth array element.
Example.java
import java.util.Arrays;
/**
* Java Example Program to Split a String
*/
public class Example {
public static void main(String[] args) {
//two strings
String str = "ab-cd-ab-ps-ai-rp-ao";
//regular expression for separator
String separator = "-";
//split string
String[] splits = str.split(separator, 4);
System.out.print(Arrays.toString(splits));
}
}
The output is:
[ab, cd, ab, ps-ai-rp-ao]
With a positive limit of 4, Java applies the delimiter at most three times. Therefore, the returned array has at most four elements, and the unsplit remainder becomes the last element.
How the limit argument changes Java split() results
The value passed as the second argument changes both the number of returned elements and the treatment of trailing empty strings.
| Limit value | Behavior |
|---|---|
limit > 0 | The regular expression is applied at most limit - 1 times. The array contains at most limit elements. |
limit = 0 | Splitting continues as needed, but trailing empty strings are removed. This is the behavior of split(regex). |
limit < 0 | Splitting continues as needed, and trailing empty strings are kept. |
Split a Java string by spaces
To split text that may contain one or more whitespace characters between words, use the regular expression \\s+. It matches one or more whitespace characters, so it is more flexible than splitting on a single literal space.
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
String text = "Java split string";
String[] words = text.split("\\s+");
System.out.println(Arrays.toString(words));
}
}
[Java, split, string]
Split a Java string by a dot
A dot has special meaning in a regular expression: it matches any character. To split on a literal dot, escape it in the regular expression. Because the regular expression itself is written inside a Java string literal, the backslash must also be escaped, giving "\\.".
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
String version = "21.0.2";
String[] parts = version.split("\\.");
System.out.println(Arrays.toString(parts));
}
}
[21, 0, 2]
Split by a literal delimiter with Pattern.quote()
If the delimiter comes from a variable and should always be treated as literal text, Pattern.quote() is safer than manually escaping regular-expression metacharacters.
import java.util.Arrays;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
String text = "one|two|three";
String delimiter = "|";
String[] parts = text.split(Pattern.quote(delimiter));
System.out.println(Arrays.toString(parts));
}
}
[one, two, three]
Keep trailing empty values when splitting a Java string
The one-argument split(regex) method removes trailing empty strings. This matters when delimiter-separated data can contain an empty final field. Pass a negative limit, such as -1, when those trailing empty values must be preserved.
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
String row = "A,B,";
System.out.println(Arrays.toString(row.split(",")));
System.out.println(Arrays.toString(row.split(",", -1)));
}
}
[A, B]
[A, B, ]
Convert the result of String.split() to a List
String.split() returns a String[]. If your code needs a List<String>, the array can be wrapped with Arrays.asList().
import java.util.Arrays;
import java.util.List;
public class Example {
public static void main(String[] args) {
String colors = "red,green,blue";
List<String> list = Arrays.asList(colors.split(","));
System.out.println(list);
}
}
[red, green, blue]
The list returned by Arrays.asList() has a fixed size. If you need to add or remove elements, create a mutable list from it.
Split a Java string at a specific index
String.split() splits around a regular-expression match; it does not accept a character index. When the requirement is to divide a string at a known position, use substring() instead.
public class Example {
public static void main(String[] args) {
String text = "JavaSplit";
int index = 4;
String first = text.substring(0, index);
String second = text.substring(index);
System.out.println(first);
System.out.println(second);
}
}
Java
Split
Common Java String split() mistakes
- Treating the delimiter as plain text: the delimiter argument is a regular expression. Escape regex metacharacters or use
Pattern.quote()for a literal delimiter. - Using
"."to split on a dot: a dot matches any character in regex. Use"\\."for a literal dot. - Expecting trailing empty fields from
split(regex): the default behavior removes them. Use a negative limit to retain them. - Reading a positive limit as the number of delimiter matches: a positive limit is the maximum number of array elements, so the delimiter is applied at most
limit - 1times. - Using
split()for an index-based cut: usesubstring()when you already know the character position.
Java String split() key points
The Java String.split() method separates a string around matches of a regular expression and returns the parts as a String[]. Use a simple delimiter directly when it has no special regex meaning, escape or quote literal regex metacharacters, and use the limit argument when you need to restrict the returned elements or preserve trailing empty values.
Concluding this Java String method tutorial, we have learned how to split a string into array of items based on a string constant separator or regular expression as separator. Also, we have learned how to limit the number of splits.
For the API definition and full method behavior, refer to the Java String documentation from Oracle.
TutorialKart.com