How to use StringTokenizer
The StringTokenizer class in Java is used to divide a string into multiple substrings. It is used as follows:
- Import the StringTokenizer class:
import java.util.StringTokenizer;
- Instantiate a StringTokenizer object:
StringTokenizer st = new StringTokenizer(str);
There, ‘str’ is the string to be split.
- Choose a delimiter (optional):
StringTokenizer st = new StringTokenizer(str, delimiters);
Delimiters are a set of characters used to separate strings. If no delimiter is specified, default separators like space, tab, newline, carriage return, and page break will be used.
- Extract substring:
// 判断是否还有子串
while (st.hasMoreTokens()) {
// 获取下一个子串
String token = st.nextToken();
}
The hasMoreTokens() method is used to check if there are more substrings, while the nextToken() method is used to retrieve the next substring.
- Get the number of substrings:
int count = st.countTokens();
You can use the countTokens() method to get the number of substrings.
- Number of specified delimiters:
st.countTokens();
You can use the countTokens() method to get the number of delimiters.
It is important to note that the StringTokenizer class is deprecated, and it is recommended to use the split() method of the String class instead.