Java StringTokenizer and String Split Example.


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

Updated on: 26-Feb-2020

808 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements