How To Split String In Java

If you want to split the String value into the different parts based on the delimiter or regular expression, String class provides split() which does the job. It has two overloaded methods with the following syntax:

  1. split(String regex) – Splits this string around matches of the given regular expression.
  2. split(String regex, int limit) – Splits this string around matches of the given regular expression.

This example demonstrates with simple example to make the string splitting easier.

package javabeat.net.core;

import java.util.Arrays;

/**
 * String Split Example
 * @author Krishna
 *
 */
public class StringSplitExample {
	public static void main(String[] args) {
		String str="This is test split string!!";

		//Split the string with whitespace
		String arr[] = str.split(" ");
		System.out.println(Arrays.toString(arr));

		//Split the string with whitespace and maximum two times
		arr = str.split(" ",2);
		System.out.println(Arrays.toString(arr));

		//Split the string with regular expressions (only numbers)
		str="This is7 testf5 split string99!!";
		arr = str.split("[0-9]");
		System.out.println(Arrays.toString(arr));

		//Split the string with regular expressions (only alphabets)
		str="345 789r 8778h 897h";
		arr = str.split("[a-z]");
		System.out.println(Arrays.toString(arr));

	}
}

Output…

[This, is, test, split, string!!]
[This, is test split string!!]
[This is,  testf,  split string, , !!]
[345 789,  8778,  897]

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*