StringTokenizer tok = new StringTokenizer("Hello how are you");
will give output as below, since space (" ") is a default delimiter
Hello
how
are
you
StringTokenizer tok = new StringTokenizer("Hello|how|are|you", "|");
will give output as below, since we have delimit as "|"
Hello
how
are
you
StringTokenizer tok = new StringTokenizer("Hello|how|are|you", "|", true);
will give output as below, true gives the delimiter along with tokens
Hello
|
how
|
are
|
you
Lets see simple example of using String Tokenizer class in Java.
import java.util.StringTokenizer;
public class StringTokenizerTest {
public static void main(String[] args) {
StringTokenizer tok = new StringTokenizer("Hello how are you");
while(tok.hasMoreTokens()){
System.out.println(tok.nextElement());
}
System.out.println("-------------------------------");
tok = new StringTokenizer("Hello|how|are|you", "|");
while(tok.hasMoreTokens()){
System.out.println(tok.nextElement());
}
System.out.println("-------------------------------");
tok = new StringTokenizer("Hello|how|are|you", "|", true);
while(tok.hasMoreTokens()){
System.out.println(tok.nextElement());
}
}
}
OUTPUT:
Hello
how
are
you
-------------------------------
Hello
how
are
you
-------------------------------
Hello
|
how
|
are
|
you
Alternate:
String Tokenizer is from legacy class and because of compatibility reasons recommended to use "split" method from String class. Lets see this "split" method in our next tutorial.
No comments:
Write comments