Pages

Sunday, 11 March 2012

String Tokenizer


String Tokenizer:-

Using StringTokenizer you can easily Split String into Tokens.
We can use StringTokenizer using following method;-
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)  
 
Here is simple Example.

 StringTokenizer strTo = new StringTokenizer("x-y-z", "-");
 while (st.hasMoreTokens()) 
 {
     System.out.println(st.nextToken());
 }
Another way:-
 for (String token : "x-y-z".split("-")) 
 {
     System.out.println(token);
 }

Simple java Example:-

public class Test {
public static void main(String[] args) {
    String str="this is=android{welcome}";
    StringTokenizer st = new StringTokenizer(str,"={}");

    System.out.println("---- Split by sp");
    while (st.hasMoreElements()) {
        String profile=st.nextElement().toString();
        String name=st.nextElement().toString();
        System.out.println("profile="+ profile +"name="+ name);
    }

    System.out.println("---- Split by comma ',' ------");
    StringTokenizer st2 = new StringTokenizer(str, ",");

    while (st2.hasMoreElements())
    {
        System.out.println(st2.nextElement());
    }
   
}
}
o/p:-
---- Split by sp
profile=this,is
name=android
other=welcome

---- Split by comma ',' ------
this
is=android{welcome}
Explanation:-

1> public int countTokens ()

Returns the number of unprocessed tokens remaining in the string.
Returns:-
number of tokens that can be retreived before an Exception will result from a call to nextToken().

2>public boolean hasMoreElements ()

Returns
  • true if unprocessed tokens remain.

3>public boolean hasMoreTokens ()

Returns
  • true if unprocessed tokens remain.

4>public Object nextElement ()

Returns the next token in the string as an Object. This method is implemented in order to satisfy the Enumeration interface.
Returns:-
next token in the string as an Object
Throws:-
NoSuchElementExceptionif no tokens remain.

5>public String nextToken (string delims)


Returns the next token in the string as a String. The delimiters used are changed to the specified delimiters.
Parameters:-
delims the new delimiters to use.
Returns
  • next token in the string as a String.
Throws
NoSuchElementExceptionif no tokens remain. 






























Thank you.. Suggestion Appreciated..

 

No comments:

Post a Comment