Mastering Java's split() Method: A Practical Guide with Code Examples
What is the split() method in Java?
The String.split() method breaks a string into an array of substrings based on a specified delimiter, which is defined by a regular expression. In most everyday use cases, the delimiter is a space or a comma, but any regex pattern can be used.
Method signature
public String[] split(String regex) public String[] split(String regex, int limit)
Parameters
- regex: A regular expression that defines the delimiter.
- limit: The maximum number of array elements to return. If omitted or zero, all possible substrings are returned. A negative limit allows trailing empty strings.
Splitting a string with a comma delimiter
For example, suppose you have the string strMain = "Alpha, Beta, Delta, Gamma, Sigma". Splitting on the comma and following space gives five separate words:
- Alpha
- Beta
- Delta
- Gamma
- Sigma
Use String.split(", ") to perform this operation.
class StrSplit {
public static void main(String[] args) {
String strMain = "Alpha, Beta, Delta, Gamma, Sigma";
String[] arrSplit = strMain.split(", ");
for (String part : arrSplit) {
System.out.println(part);
}
}
}
Output
Alpha Beta Delta Gamma Sigma
Using a limit to control the split
Sometimes you only need the first few elements and want the remainder to stay together. The limit parameter lets you do that. With a limit of 3, the third element contains the rest of the string:
- Alpha
- Beta
- Delta, Gamma, Sigma
class StrSplitWithLimit {
public static void main(String[] args) {
String strMain = "Alpha, Beta, Delta, Gamma, Sigma";
String[] arrSplit = strMain.split(", ", 3);
for (String part : arrSplit) {
System.out.println(part);
}
}
}
Output
Alpha Beta Delta, Gamma, Sigma
Splitting a string by spaces
To divide a sentence into individual words, you can split on a single space. For example:
public class SplitBySpace {
public static void main(String[] args) {
String strMain = "Welcome to Guru99";
String[] arrSplit = strMain.split(" ");
for (String word : arrSplit) {
System.out.println(word);
}
}
}
Output
Welcome to Guru99
Java
- Master Java String Manipulation: Essential Functions, Methods, and Practical Examples
- Java String length() Method: How to Get a String’s Size (Example)
- Mastering Java String.indexOf(): Locating Substrings & Practical Examples
- Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
- Mastering Java's String compareTo() Method: Syntax, Use Cases, and Practical Examples
- Java String.contains() Method: How to Check for Substrings – Practical Examples
- Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
- Java Abstraction: Mastering Abstract Classes, Methods, and Practical Examples
- Java Interfaces Explained: How to Define and Implement Them with Practical Examples
- Reading Files in Java with BufferedReader – A Practical Guide with Examples