Split String in Java

There are different ways to Split the String in Java, out of which some common ways are shown to Split String in Java.

Here in this Example We will Split the String using the String Split Method

public class SplitString {

	public static void main(String[] args){
		
		String str = "java-language";
		
		String[] parts = str.split("-");
		
		String part1 = parts[0];
		
		String part2 = parts[1];
		
		System.out.println("part1 "+part1);
		
		System.out.println("part2 "+part2);
	}
}

output:-
split string in java

 

Split method takes a regular expression, so we have to escape special characters if required. For Example if you want to split on period or dot . use either backslash \ to escape the individual special character like so split(“\\.”), or use character class [] to represent literal character(s) like so split(“[.]”), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(“.”)).

We can also split the String using the StringTokenizer class as shown in Example

import java.util.StringTokenizer;

public class SplitStringTokinizer {

	public static void main(String[] args){
		
		String str = "java-language";
		
		StringTokenizer stringTokenizer = new StringTokenizer(str, "-");
		
		while(stringTokenizer.hasMoreElements()){
			
			System.out.println(stringTokenizer.nextToken());
		}
	}
}

StringTokenizer class is a legacy class and retain for Compatibility Reason. It is Preferred to use Split over StringTokenizer class.

Leave a Comment