Java split() method
Java split() method
The Java split() method is used to divide a string into an array of substrings based on a specified delimiter. This is useful when you need to break a string into parts, such as parsing data from a CSV file or processing a text based on a particular pattern
This method splits the original string against the given regular expression and returns an array of String objects, each containing a substring of the original string.
split method signatures
The signature of the split() method is given below:
public String[] split(String regex)
public String[] split(String regex, int limit)
regex: regular expression to be applied on the string.
limit: limit for the number of strings in the array. If it is zero, it will return all the strings matching regex.
Example
Let’s understand the use of the split() method with the help of an example program.
package com.testingdocs.stringmethods;
public class ExampleProgram {
public static void main(String[] args) {
String str = "Apple,Banana,Grapes,Oranges";
// Split the string by commas
String[] fruits = str.split(",");
// print each fruit
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Program Output
The program output is as follows:
Apple
Banana
Grapes
Oranges
In the example, str.split(“,”) splits the string into an array of substrings using the comma , as the delimiter.
The resulting array fruits contains:
[“Apple”, “Banana”, “Grapes”, “Oranges”]
Java Tutorials
Java Tutorial on this website:
For more information on Java, visit the official website :