Tutorials

Java String


Java String Tokenizer


StringTokenizer is present in java.util package.

 

StringTokenizer allows us to break the given String at the specified delimiter into tokens. Example explained below will help you get more details about it.

String str = "Let the world hear your silence";

StringTokenizer tokens = new StringTokenizer(str , " ");

 

StringTokenizer will break the input string (str) at the given delimiter.  In StringTokenizer first parameter (str) is the original string on which the operation would be performed. Second parameter (“ “) is the delimiter.

So here the string will be broken at space. And each broken words will be stored in tokens variable.

Example:

 

import java.util.StringTokenizer;

 

public class StrToken {

 

      public static void main(String[] args) {

            String string = "Let the world hear your silence";

           

            StringTokenizer tokens = new StringTokenizer(string, " ");

 

            while(tokens.hasMoreTokens()){

                  System.out.println(tokens.nextToken());

            }

      }

}

OUTPUT:

Let

the

world

hear

your

silence

 

In the output section we can clearly see that original string is broken at space (“  “).

hasMoreTokens: This checks if more token (broken word) still exists in the variable tokens or not.

nextTokens(): This will fetch the immediate next token from String Tokenizer object.

Drawbacks:

 

 

StringTokenizer class is deprecated right now. split() method of String class is recommended to be used instead of StringTokenizer.

 



Please Share this page
Views : 84
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!