How to use StringTokenizer in java ?

StringTokenizer (java.util.StringTokenizer) is java utility used to break a String into tokens on the basis of character or set of character (delimiter). These characters can be specified at the time of creation of StringTokenizer or per token basis.

Now lets see simple example of of StringTokenizer

String test = "a=b=c=d=e" ;

StringTokenizer st = new StringTokenizer(test, "=");
while (st.hasMoreTokens()) {
String token = st.nextToken();

System.out.println( token );
}


output :

a
b
c
d
e

StringTokenizer comes with three important methods which we have used in above code :

1. hasMoreTokens()

This method test whether at least one token exists after the current position , if find at least one token after the current position then it returns true else it returns false.

2. nextToken()

This method returns next token after the current position, if it do not find the element then it throws NoSuchElementException.

3. countTokens()

This method determines how many times we can call nextToken without really getting the NoSuchElementException.


Also there is one form of nextToken method which takes delimiter as an argument. This delimiter is used after the current position and if not changed again it acts like default.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment