In this guide, you will learn how to split a string in java with delimiter. There are three ways you can split a string in java, first and preferred way of splitting a string is using the split() method of string class. The second way is to use the Scanner class. Other way is using the StringTokenizer class, which is a legacy class and not recommended anymore.
Three ways to Split a String in Java with Delimiter
- Using split() method of String class
- Using Scanner class useDelimiter() method
- Using StringTokenizer class
1. Using split() method of String class
This method has following two variants:
- split(String regex)
- split(String regex, int limit)
Example of split(String regex): We can pass a regular expression (regex) as delimiter in this method. In the following example, we are passing comma ( , ) in this method to break the string using comma as delimiter. You can pass any delimiter such as dot ( . ), hyphen( – ), whitespace (” “), pipe ( | ), any character or string.
public class JavaExample { public static void main(String args[]) { //string that contains comma String str = "Steve, Ram and Paul"; //We want to break the string using comma, so delimiter is //specified as comma. You can break the the string using //any delimiter such as dot, backslash, pipe, tab etc String[] strArray = str.split(","); for(String s: strArray){ System.out.println(s); } } }
Output:
Example 2: Passing a regular expression to break the input string using multiple delimiters.
public class JavaExample { public static void main(String args[]) { String str = "This is a String,with.multiple|delimiters"; //breaking the string using multiple delimiters //pass all the delimiters, you want to use inside //double quotes. Here, we passing dot, comma and pipe char //and a space as delimiters. String[] strArray = str.split("[,.| ]"); for(String s: strArray){ System.out.println(s); } } }
Output:
Example of split(String regex, int limit): This is second variant of split() method.
public class JavaExample { public static void main(String args[]) { String str = "hi/hello/bye///"; //limit is positive String[] strArray = str.split("/", 2); System.out.println("Limit is Positive:"); int i=1; for(String s: strArray){ System.out.print(i+". "); System.out.println(s); i++; } //limit is negative String[] strArray2 = str.split("/", -5); System.out.println("Limit is Negative:"); int j=1; for(String s2: strArray2){ System.out.print(j+". "); System.out.println(s2); j++; } //limit is zero String[] strArray3 = str.split("/", 0); System.out.println("Limit is zero:"); int k=1; for(String s3: strArray3){ System.out.print(k+". "); System.out.println(s3); k++; } } }
Output:
Split String using Pipe Symbol:
public class JavaExample { public static void main(String args[]) { String str = "Welcome|Home"; String[] strArray = str.split("|"); for(String s: strArray){ System.out.println(s); } } }
Output: This produced the unexpected output. Instead of breaking the string using pipe symbol, it splits the string into single characters. In the next program, we will fix this.
W e l c o m e | H o m e
The reason that we got the above output is because this regular expression is evaluated as a logical OR operator, instead of a pipe symbol. To fix this, you can either use escape sequence like this: str.split(“\\|”) or use the brackets like this: str.split(“[|]”). Let’s see the program with escape sequence:
public class JavaExample { public static void main(String args[]) { String str = "Welcome|Home"; //Now we are using escape sequence before the pipe //You can also call method like this: //str.split("[|]") String[] strArray = str.split("\\|"); for(String s: strArray){ System.out.println(s); } } }
Output:
Welcome Home
2. Using Scanner class useDelimiter() method
Scanner.next() method: It splits the string using the whitespace as a default delimiter. You cannot specify a delimiter in Scanner.next() method. To specify a delimiter, you can use the useDelimiter() method of Scanner class.
import java.util.Scanner; public class JavaExample { public static void main(String[] args) { String str="Welcome to BeginnersBook.com"; Scanner scan = new Scanner(str); //break the string using whitespace while (scan.hasNext()) { System.out.println(scan.next()); } scan.close(); } }
Output:
Welcome to BeginnersBook.com
Scanner.useDelimiter() method: You can specify a delimiter and then read the substrings using Scanner.next() method. In the following example, we have provided multiple delimiters (space and dot) inside brackets.
import java.util.Scanner; public class JavaExample { public static void main(String[] args) { String str="Welcome to BeginnersBook.com"; Scanner scan = new Scanner(str); //whitespace and dot delimiters are inside brackets scan.useDelimiter("[ .]"); while (scan.hasNext()) { System.out.println(scan.next()); } scan.close(); } }
Output:
3. Using StringTokenizer class
StringTokenizer is a legacy class that belongs to java.util package. We can use this class to break a string into multiple substrings, called tokens.
There are two methods that come into play while using this class:
public boolean hasMoreTokens(): This method returns a boolean value true or false. It returns true if a substring is available to be read by nextToken() method.
public String nextToken(): It returns the token and moves to the next token.
import java.util.StringTokenizer; public class JavaExample { public static void main(String[] args) { String str = "100-200-300"; //specify the delimiter in constructor of StringTokenizer class StringTokenizer strTokens = new StringTokenizer(str, "-"); //checks if the next token is present while (strTokens.hasMoreTokens()) { //displays the token System.out.println(strTokens.nextToken()); } } }
Output:
100 200 300
FAQ
A delimiter is a character or a symbol that marks the beginning and end of a sub-data unit inside a main data unit. In context of strings, a delimiter marks the beginning and end of a substring.
The String.split() method is the best way of splitting a string in Java. This method is robust, easy to use and supports regular expression (regex). Using regex, we can specify multiple delimiters inside split() method.
String.split() method returns an array of string type. The elements of string array, represents the substrings that we get after using split() method.