Java String split() Method
Example
Split a string into an array of strings:
String myStr = "Split a string by spaces, and also punctuation.";
String regex = "[,\\.\\s]";
String[] myArray = myStr.split(regex);
for (String s : myArray) {
System.out.println(s);
}
Definition and Usage
The split()
method splits a string into an array of substrings using a regular expression as the separator.
If a limit is specified, the returned array will not be longer than the limit. The last element of the array will contain the remainder of the string, which may still have separators in it if the limit was reached.
Tip: See the Java RegEx tutorial to learn about regular expressions.
Syntax
One of the following:
public String[] split(String regex, int limit)
public String[] split(String regex)
Parameter Values
Parameter | Description |
---|---|
regex | Required. A regular expression defining the separators where the string is split. |
limit | Optional. The maximum length of the returned array. |
Technical Details
Returns: | A String array. |
---|---|
Throws: | PatternSyntaxException - If the syntax of the regular expression is incorrect. |
Java version: | 1.4 |
❮ String Methods