HTML Java

Java String Tokenizer


String Tokenizer

Its a utility class which is found in java.util package.


What does this class do?

This will take String from you annd break it from the particular point then represent it again as you want or we can say then we can perform task on it then we can use this class.


String Tokenizer Constrctors

  • StringTokenizer(String s): Creates StringTokenizer with given String and it split by default space, line, tab.
  • StringTokenizer(String s, String delim): Creates StringTokenizer with given delim expression.
  • StringTokenizer(String s, String delim, boolean flag): Creates String Tokenizer with given delim expression and if flag is false then its not consider delim as a token if flag is true then its consider delimeter as tokens.

String Tokenizer Methods

  • boolen hasMoreTokens(): Check whether more tokens are available or not.
  • String nextToken(): Return the next token from the Stringtokenizer object.
  • String nextToken(String delim): Return the next token on the basis of delimeter.
  • boolean hasMoreElements(): Check whether more token are available or not.
  • Object nextToken(): It is similar to nextToken() method, but its return type is Object.
  • int countTokens(): Its use to get the number of token from the StringTokenizer object. This method return no tokens.

Example

Package com.string;

import java.util.StringTokenizer;

public class StringTokens {

public static void main(String[] args) {

System.out.println("constructor type 1");
StringTokenizer str1 = new StringTokenizer("Hello coders How are you ?");
while (str1.hasMoreTokens()) {
System.out.println(str1.nextToken());
}

System.out.println("constructor type 1 but delim use by nextToken(-)");
StringTokenizer str2 = new StringTokenizer("Hello-geeks-How-are-you?");
while (str2.hasMoreElements()) {
System.out.println(str2.nextToken("-"));
}

System.out.println("constructor type 3");
StringTokenizer str3 = new StringTokenizer("Hello-artists-How-are-you?", "-", true);
while (str3.hasMoreElements()) {
System.out.println(str3.nextToken());
}

System.out.println("constructor type 3");
StringTokenizer str4 = new StringTokenizer("Hello developer How are you?", " ", false);
while (str4.hasMoreTokens()) {
System.out.println(str4.nextToken());
}

System.out.println("constructor type 2");
StringTokenizer str5 = new StringTokenizer("Hello/designer/How are/you?", "/");
while (str5.hasMoreTokens()) {
System.out.println(str5.nextToken());
}

}

}
Try it »


String Tokenizer for multiple

Example

package com.string;
import java.util.*;
public class StringTokensMulltipleDelim {

public static void main(String[] args) {
String url = "https://codersarts.com/java-initerview-questions";

StringTokenizer multiTokenizer = new StringTokenizer(url,"://./-");

while (multiTokenizer.hasMoreTokens()) {
System.out.println(multiTokenizer.nextToken());
}
}
}
Try it »