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:
- split(String regex) – Splits this string around matches of the given regular expression.
- 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]