How to randomly access nth element in StringTokenizer

jem picture jem · Nov 15, 2011 · Viewed 7k times · Source

Is there anyway we can directly access a certain(lets say 20th) element in a stringTokenizer. Every now and then I need only a certain element from it and do not need others, yet I have to traverse through all elements.

EDIT: I also want to ignore empty elements.

Am I missing something?

Answer

Pablo Santa Cruz picture Pablo Santa Cruz · Nov 15, 2011

You can use String.split for that instead of a Tokenizer.

For example:

String[] split = "you string is splitting".split(" ");
split[2];  // random access to the 3rd element of split    

Of course, you will need to check that your split actually has that many elements before accessing its subindex.