The split() method of the String class accepts a regular expression, splits the current input text into tokens and returns them as a string array.
Example
import java.util.Scanner;
public class Example{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String[] strArray = input.split("\\d");
for (int i=0; i<strArray.length; i++) {
System.out.println(strArray[i]);
}
}
}Output
Enter input text: 1Ramu 2Raju 3Radha 4Rahman 5Rachel Ramu Raju Radha Rahman Rachel
Splitting a string using Java.util.regex package −
Example
You can also spilt a String using the split() method of the patter class. this method accepts a string and splits it into tokens based on the underlying regular expressions and returns them as a string array.
import java.util.Scanner;
import java.util.regex.Pattern;
public class SplittingString{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\\d";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
String[] strArray = pattern.split(input);
for (int i=0; i<strArray.length; i++) {
System.out.println(strArray[i]);
}
}
}Output
Enter input text: 1Ramu 2Raju 3Radha 4Rahman 5Rachel Ramu Raju Radha Rahman Rachel