Java StringTokenizer and String Split Example.

Java 8Object Oriented ProgrammingProgramming

The StringTokenizer class allows an application to break a string into tokens.

This class is a legacy class that is retained for compatibility reasons although its use is discouraged in new code.

Example

Live Demo

import java.util.*;
public class Sample {
   public static void main(String[] args) {
      // creating string tokenizer
      StringTokenizer st = new StringTokenizer("Come to learn");

      // counting tokens
      System.out.println("Total tokens : " + st.countTokens());

      // checking tokens
      while (st.hasMoreTokens()) {
         System.out.println("Next token : " + st.nextToken());
      }
   }
}

Output

Total tokens : 3
Next token : Come
Next token : to
Next token : learn

The split() method of the String class splits this string around matches of the given regular expression.

Example

Live Demo

import java.io.*;
public class Test {
   public static void main(String args[]) {
      String Str = new String("Welcome-to-Tutorialspoint.com");
      System.out.println("Return Value :" );

      for (String retval: Str.split("-")) {
         System.out.println(retval);
      }
   }
}

Output

Return Value :
Welcome
to
Tutorialspoint.com
raja
Published on 12-Feb-2018 07:15:56
Advertisements