How to split a String in Java
There are three better ways to split a string in Java.
- Using split() method of String Class
- Using StringTokenizer class of java.util package.
- Using useDelimiter() of Scanner Class.
Using split() method of String Class
Syntax
public String[] split(String regex, int limit) or public String[] split(String regex)
** Tutorial**
package com.javaindetail.splittutorial;
public class SplitTutorial {
public static void main(String[] args) {
String Str = new String("Welcome-to-javaindetail.com");
System.out.println("Using limit 2 :" );
for (String str: Str.split("-", 2)){
System.out.println(str);
}
System.out.println("");
System.out.println("Using limit 0 :" );
for (String str: Str.split("-", 0)){
System.out.println(str);
}
System.out.println("");
System.out.println("without limit :" );
for (String str: Str.split("-")){
System.out.println(str);
}
}
}
Output
Using limit 2 :
Welcome
to-javaindetail.com
Using limit 0 :
Welcome
to
javaindetail.com
without limit :
Welcome
to
javaindetail.com
Using StringTokenizer class of java.util package.
Syntax:
public StringTokenizer(String str) or public StringTokenizer(String str, String delim) or public StringTokenizer(String str, String delim, boolean returnDelims)
** Tutorial**
package com.javaindetail.splittutorial;
import java.util.StringTokenizer;
public class SplitUsingTokenizer {
public static void main(String[] args) {
String str = "welcome-to-javaindetail.com";
StringTokenizer strToken = new StringTokenizer(str, "-");
System.out.println("Splitting using StringTokenizer with - as delimiter");
while (strToken.hasMoreTokens()) {
System.out.println(strToken.nextElement());
}
}
}
Output
Splitting using StringTokenizer with - as delimiter
welcome
to
javaindetail.com
Using useDelimiter() of Scanner Class.
Syntax:
Scanner scanner = new Scanner(string).useDelimiter(delimiter);
Tutorial
package com.javaindetail.splittutorial;
import java.util.Scanner;
public class SplitUsingScanner {
public static void main(String[] args) {
String str = "welcome-to-javaindetail.com";
Scanner scanner = new Scanner(str).useDelimiter("-");
while (scanner.hasNext())
System.out.println(scanner.next());
scanner.close();
}
}
Output
welcome
to
javaindetail.com
Enjoy Reading This Article?
Here are some more articles you might like to read next: