最佳答案StringTokenizerWhat is StringTokenizer? StringTokenizer is a class in Java that is used to break a string into smaller parts, known as tokens. It is part of the...
StringTokenizer
What is StringTokenizer?
StringTokenizer is a class in Java that is used to break a string into smaller parts, known as tokens. It is part of the java.util package and provides an efficient way to parse strings.
Working of StringTokenizer
The StringTokenizer class takes a string and splits it into tokens based on a delimiter. The delimiter is specified when creating an instance of the class. By default, the delimiter is set to space, but it can be customized to any character or set of characters.
Let's take an example to understand how StringTokenizer works:
String str = \"Hello, World! How are you?\";StringTokenizer st = new StringTokenizer(str);while (st.hasMoreTokens()) { System.out.println(st.nextToken());}
Output:
Hello,World!Howareyou?
As we can see in the example above, the delimiter used is the space character. So, the string is split at each space and the resulting tokens are printed.
Methods in StringTokenizer
The StringTokenizer class provides various methods to work with tokens:
1. boolean hasMoreTokens(): This method returns true if there are more tokens available in the string, otherwise, it returns false.
2. String nextToken(): This method returns the next token in the string. It throws a NoSuchElementException if there are no more tokens.
3. int countTokens(): This method returns the number of remaining tokens in the string.
4. String nextToken(String delimiters): This method returns the next token using the specified delimiters instead of the default delimiter.
Let's use some of these methods in an example:
String str = \"Apple,Orange,Mango\";StringTokenizer st = new StringTokenizer(str, \",\");System.out.println(\"Number of tokens: \" + st.countTokens());while (st.hasMoreTokens()) { System.out.println(st.nextToken());}
Output:
Number of tokens: 3AppleOrangeMango
In the example above, the delimiter used is a comma. The countTokens() method returns the number of tokens, and the nextToken() method is used to print each token.
Advantages and Disadvantages of StringTokenizer
Advantages:
- Simple and easy to use.
- Efficient for basic string parsing.
Disadvantages:
- Does not support regular expressions.
- Cannot handle multiple delimiters at once.
- Does not provide methods for retrieving the delimiter used.
Due to these limitations, String.split() method or regular expressions are often preferred over StringTokenizer for more complex string parsing.
Conclusion
StringTokenizer is a useful class in Java for basic string parsing. It allows you to split a string into smaller parts based on a specified delimiter. However, it has some limitations compared to other methods like String.split() or regular expressions. It is important to choose the appropriate method based on the complexity of the parsing requirements.