
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java StringTokenizer and String Split Example
Both StringTokenizer class and the split() method in Java are used to divide a string into tokens or substrings. However, they are different from each other. The StringTokenizer class does not support regular expressions, whereas the split() method works with regular expressions.
In this article, we will see some Java examples that show how to split strings using them.
Example Scenario:
Input: str = "simple easy learning" Output: split_str = "simple", "easy", "learning"
Splitting String using StringTokenizer Class
The StringTokenizer is a legacy class of java.util package. This class provides methods to break a string into multiple tokens. It is a legacy class that is retained for compatibility reasons although its use is discouraged in newer version of Java.
In older version of Java, some classes and interfaces were used at the place of collection framework to store collection of objects. These classes are called as legacy class.
Example
The following example demonstrates the use of StringTokenizer class.
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()); } } }
When you execute the above code, it will display the following output ?
Total tokens : 3 Next token : Come Next token : to Next token : learn
Splitting String using split() Method
The split() method of the String class accepts a string representing a regular expression as a parameter value and splits this string from matches of the given regular expression.
Example
In this Java program, we are illustrating the use of String spilt() method.
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); } } }
On running this code, you will get the following output ?
Return Value : Welcome to Tutorialspoint.com