Skip to content

Java StringTokenizer – Get Tokens by Index Example

Java StringTokenizer – get tokens by index example shows how to get specific tokens using the index after the string content is tokenized using the StringTokenizer object.

How to get StringTokenizer tokens using the index?

The StringTokenizer class generates the tokens from the string content using the set of delimiters. The generated tokens then can be accessed using the nextToken or the nextElement method. Plus there are a couple of methods, namely hasMoreTokens and hasMoreElements, that let us know that whether there are more tokens left in the string content.

By combining these methods, we can iterate through the generated string tokens as given below.

Output

Except for these methods, the StringTokenizer class does not provide any methods that let us access the generated tokens using their index. However, we can do that by writing a custom method that returns a list of tokens or an array of tokens. Once we get the list or an array of tokens, we can access the specific tokens using the index.

Here is an example code for that.

Output

Is this the recommended way to get string tokens by index?

NO. It is not. The StringTokenizer class is a legacy class that is retained only for backward compatibility purposes. You should use the String split method instead of the StringTokenizer whenever possible.

See below example where I have tokenized the same string using the split method. The split method returns an array of tokens, so we do not need to create any workarounds for the purpose of accessing the elements by index.

Output

If you want to learn more about the tokenizer, please visit the Java StringTokenizer Tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.