StringTokenizer st = new StringTokenizer("hello world"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); }
String input = "one two three four"; StringTokenizer st = new StringTokenizer(input); int numTokens = 0; while (st.hasMoreTokens()) { numTokens++; st.nextToken(); } System.out.println("There are " + numTokens + " tokens in the input string.");This code creates a StringTokenizer object with the input string "one two three four" and counts the number of tokens by incrementing a counter variable for every token that has moreTokens() returns true for. The loop then discards each token using nextToken(), and the final output is the number of tokens in the input string ("There are 4 tokens in the input string."). Overall, StringTokenizer is a useful class for processing strings into tokens based on delimiters. The hasMoreTokens() method is a key method for determining when there are no more tokens left to process.