Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - StringTokenizer


Say, you want to break an existing String based on a character. This is exactly where StringTokenizer comes handy.


Let us understand StringTokenizer with the below example,


Say, we have a String separated by comma ,.


Hello,Beautiful,World

And we want to break Hello,Beautiful,World into three Strings (i.e. Hello , Beautiful and World).


Let us see it in the below working code.


Example :



import java.util.StringTokenizer;

public class MyApplication {
    public static void main(String[] args) {

        StringTokenizer x = new StringTokenizer("Hello,Beautiful,World", ",");

        while (x.hasMoreTokens()) {
            System.out.println(x.nextToken());
        }
    }
}


Output :



  Hello
  Beautiful
  World

So, in the above code we have created a StringTokenizer object and initialised it with the String Hello,Beautiful,World.


Also we have mentioned the delimiter as , so that the String Hello,Beautiful,World creates new Strings based on comma ,.

Spring_Boot

Then in the next line, we have used the x.hasMoreTokens() with the while() loop. Which says, be in the loop until there is a delimiter (i.e. comma , in this case).


while (x.hasMoreTokens()) {
	System.out.println(x.nextToken());
}

And the print statement has the x.nextToken() method, which prints the individual Strings as output.

Output :



  Hello
  Beautiful
  World