You can use the split() method of the String class to split a string into tokens based on delimiters.

The split() method accepts a regular expression as a delimiter.

The following code illustrates how to use the split() method of the String class.


public class Main {
  public static void main(String[] args) throws Exception {
    // Split the same string using String.split() method
    String str = "this is a  test from book";
    System.out.println("\nTokens using the String.split() method:");
    String regex = "[ ,]+"; /* a space or a comma */
    String[] s = str.split(regex);
    for (int i = 0; i < s.length; i++) {
      System.out.println(s[i]);//from   w ww.j  a  v  a 2  s  .  c om


Related Topic