In Java, the split() method of the String class is used to split a string into an array of substrings based on a specified delimiter. The best example of this is CSV (Comma Separated Values) files.
Program to Split a String with Delimiter in Java
Here is a simple program to split a string with a comma delimiter in Java using the split() method:
// Java program to split a string with a Comma delimiter
public class SplitString {
public static void main(String[] args) {
// Declare a string with comma delimiter
String s = "Hello,Good,Morning";
// Split the string using comma as the delimiter
String[] b = s.split(",");
// Print each fruit on a new line
for (String a : b) {
System.out.println(a);
}
}
}
Output
Hello Good Morning
Other Ways to Split a String with Delimiter in Java
Apart from the simple method demonstrated above, there are few more methods which we can use to split the string in Java.
Using String Tokenizer class
The String Tokenizer class in Java is present in java.util package. The main purpose of String Tokenizer is to divide or break the given strings into several tokens based upon the delimiter.
Example:
// Java program to split a string with delimeter using String Tokenizer Class
import java.util.StringTokenizer;
public class StringTokenizerExample {
public static void main(String[] args) {
// Creating a new string tokenizer object with given input string
StringTokenizer st = new StringTokenizer("Java Programming");
System.out.println("No. of tokens:" +st.countTokens());
// Iterate through token and print each token
while (st.hasMoreTokens())
{
// Get next token and print it with space
System.out.println("" +st.nextToken());
}
}
}
Output
No. of tokens:2 Java Programming
Using Scanner Class
The Scanner class in Java allow a user to read input from the keyboard. Scanner class is used to tokenize an input string. Java Scanner class is present in java.util package.
Example:
// Java program to split a string with delimeter using String Scanner Class
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
String s = "Geeks For Geeks";
// Create a Scanner object with input string
Scanner sc = new Scanner(s);
System.out.println("");
// Iterate through token and print each token
while(sc.hasNext())
{
System.out.println(sc.next());
}
}
}
Output
Geeks For Geeks